国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

跟我學(xué)AngularJs:Directive指令用法解讀(上)

2019-11-09 17:46:14
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

 林炳文Evankaka原創(chuàng)作品。轉(zhuǎn)載請(qǐng)注明出處http://blog.csdn.net/evankaka

本教程使用AngularJS版本:1.5.3

AngularJs GitHub: https://github.com/angular/angular.js/

AngularJs下載地址:https://angularjs.org/

       摘要: Directive(指令)筆者認(rèn)為是AngularJ非常強(qiáng)大而有有用的功能之一。它就相當(dāng)于為我們寫了公共的自定義DOM元素或CLASS屬性或ATTR屬性,并且它不只是單單如此,你還可以在它的基礎(chǔ)上來(lái)操作scope、綁定事件、更改樣式等。通過(guò)這個(gè)Directive,我們可以封裝很多公共指令,比如分頁(yè)指令、自動(dòng)補(bǔ)全指令等等。然后在HTML頁(yè)面里只需要簡(jiǎn)單的寫一行代碼就可以實(shí)現(xiàn)很多強(qiáng)大的功能。一般情況下,需要用Directive有下面的情景:

1. 使你的Html更具語(yǔ)義化,不需要深入研究代碼和邏輯即可知道頁(yè)面的大致邏輯。2. 抽象一個(gè)自定義組件,在其他地方進(jìn)行重用。

一、Directive的定義及其使用方法

AngularJs的指令定義大致如下

[html] view plain copy 在CODE上查看代碼片angular.module("app",[]).directive("directiveName",function(){      return{       //通過(guò)設(shè)置項(xiàng)來(lái)定義      };  })  Directive可以放置于元素名、屬性、class、注釋中。下面是引用myDir這個(gè)directive的等價(jià)方式。(但很多directive都限制為“屬性”的使用方式)

[html] view%20plain copy <span <span style="font-family: Arial, Helvetica, sans-serif;">directive-name</span><span style="font-family: Arial, Helvetica, sans-serif;">="exp"></span>//屬性</span>    <span class="<span style="font-family: Arial, Helvetica, sans-serif;">directive-name</span>: exp;"></span>//class    <<span style="font-family: Arial, Helvetica, sans-serif;">directive-name</span>></<span style="font-family: Arial, Helvetica, sans-serif;">directive-name</span>>//元素    <!-- directive: <span style="font-family: Arial, Helvetica, sans-serif;">directive-name </span><span style="font-family: Arial, Helvetica, sans-serif;">exp -->//注釋</span>  如下一個(gè)實(shí)例%20:

[html] view%20plain copy <!DOCTYPE html>  <html lang="zh" ng-app="myApp">  <head>      <meta charset="UTF-8">      <title>AngularJS入門學(xué)習(xí)</title>      <scr

下面是一個(gè)directive的詳細(xì)版

[html] view plain copy 在CODE上查看代碼片var myModule = angular.module(...);    myModule.directive('directiveName', function factory(injectables) {     var directiveDefinitionObject = {       E(元素):<directiveName></directiveName>  A(屬性):<div directiveName='expression'></div>  C(類): <div class='directiveName'></div>  M(注釋):<--directive:directiveName expression-->  

一般情況下E/A/C用得比較多。2.priority(數(shù)字),可選參數(shù),指明指令的優(yōu)先級(jí),若在單個(gè)DOM上有多個(gè)指令,則優(yōu)先級(jí)高的先執(zhí)行;3.terminal(布爾型),可選參數(shù),可以被設(shè)置為true或false,若設(shè)置為true,則優(yōu)先級(jí)低于此指令的其他指令則無(wú)效,不會(huì)被調(diào)用(優(yōu)先級(jí)相同的還是會(huì)執(zhí)行)4.template(字符串或者函數(shù))可選參數(shù),可以是:(1)一段HTML文本[html] view%20plain copy <!DOCTYPE html>  <html lang="zh" ng-app="myApp">  <head>      <meta charset="UTF-8">      <title>AngularJS入門學(xué)習(xí)</title>      <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  </head>  <body>  <hello-world></hello-world>  </body>  <script type="text/javascript">  var app = angular.module('myApp', []);  app.directive('helloWorld', function() {      return {          restrict: 'E',          template: '<div><h1>Hi 我是林炳文~~~</h1></div>',          replace: true      };  });  </script>  </html>  (2)一個(gè)函數(shù),可接受兩個(gè)參數(shù)tElement和tAttrs其中tElement是指使用此指令的元素,而tAttrs則實(shí)例的屬性,它是一個(gè)由元素上所有的屬性組成的集合(對(duì)象)形如:[html] view plain copy 在CODE上查看代碼片<hello-world2 title = '我是第二個(gè)directive'></hello-world2>  

其中title就是tattrs上的屬性

下面讓我們看看template是一個(gè)函數(shù)時(shí)候的情況

[html] view%20plain copy <!DOCTYPE html>  <html lang="zh" ng-app="myApp">  <head>      <meta charset="UTF-8">      <title>AngularJS入門學(xué)習(xí)</title>      <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  </head>  <body>  <hello-world></hello-world>  <hello-world2 title = '我是第二個(gè)directive'></hello-world2>  </body>  <script type="text/javascript">  var app = angular.module('myApp', []);  app.directive('helloWorld', function() {      return {          restrict: 'E',          template: '<div><h1>Hi 我是林炳文~~~</h1></div>',          replace: true      };  });  app.directive("helloWorld2",function(){                  return{                   restrict:'EAC',                   template: function(tElement,tAttrs){                      var _html = '';                      _html += '<div>' +'hello '+tAttrs.title+'</div>';                      return _html;                   }       };   });  </script>  </html>  結(jié)果:

可以看到指令中還用到了hello-world2中的標(biāo)簽中的 title字段

5.templateUrl(字符串或者函數(shù)),可選參數(shù),可以是

(1)一個(gè)代表HTML文件路徑的字符串

(2)一個(gè)函數(shù),可接受兩個(gè)參數(shù)tElement和tAttrs(大致同上)

注意:在本地開(kāi)發(fā)時(shí)候,需要運(yùn)行一個(gè)服務(wù)器,不然使用templateUrl會(huì)報(bào)錯(cuò) Cross Origin Request Script(CORS)錯(cuò)誤。由于加載html模板是通過(guò)異步加載的,若加載大量的模板會(huì)拖慢網(wǎng)站的速度,這里有個(gè)技巧,就是先緩存模板

你可以再你的index頁(yè)面加載好的,將下列代碼作為你頁(yè)面的一部分包含在里面。

[html] view plain copy 在CODE上查看代碼片<script type='text/ng-template' id='hello.html'>            <div><h1>Hi 我是林炳文~~~</h1></div>  </script>  

這里的id屬性就是被設(shè)置在templateUrl上用的。

[html] view%20plain copy <!DOCTYPE html>  <html lang="zh" ng-app="myApp">  <head>      <meta charset="UTF-8">      <title>AngularJS入門學(xué)習(xí)</title>      <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  </head>  <body>  <hello-world></hello-world>  </body>  <script type="text/javascript">  var app = angular.module('myApp', []);  app.directive('helloWorld', function() {      return {          restrict: 'E',          templateUrl: 'hello.html',          replace: true      };  });  </script>  <script type='text/ng-template' id='hello.html'>            <div><h1>Hi 我是林炳文~~~</h1></div>  </script>  </html>  輸出結(jié)果:

另一種辦法緩存是:

[html] view plain copy 在CODE上查看代碼片app.run(["$templateCache", function($templateCache) {    $templateCache.put("hello.html",      "<div><h1>Hi 我是林炳文~~~</h1></div>");  }]);  使用實(shí)例如下:

[html] view%20plain copy <!DOCTYPE html>  <html lang="zh" ng-app="myApp">  <head>      <meta charset="UTF-8">      <title>AngularJS入門學(xué)習(xí)</title>      <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  </head>  <body>  <hello-world></hello-world>  </body>  <script type="text/javascript">  var app = angular.module('myApp', []);  app.directive('helloWorld', function() {      return {          restrict: 'E',          templateUrl: 'hello.html',          replace: true      };  });  app.run(["$templateCache", function($templateCache) {    $templateCache.put("hello.html",      "<div><h1>Hi 我是林炳文~~~</h1></div>");  }]);  </script>  </html>  結(jié)果:

 其實(shí)第一種方法還好一些,寫起來(lái)會(huì)比較快,筆者就得最多的也是第一種寫法,直接包在scprit當(dāng)中

 6.replace

(布爾值),默認(rèn)值為false,設(shè)置為true時(shí)候,我們?cè)賮?lái)看看下面的例子(對(duì)比下在template時(shí)候舉的例子)

                 

 replace為true時(shí),hello-world這個(gè)標(biāo)簽不在了,反之,則存在。

7.scope

(1)默認(rèn)值false。表示繼承父作用域;

(2)true。表示繼承父作用域,并創(chuàng)建自己的作用域(子作用域);

(3){}。表示創(chuàng)建一個(gè)全新的隔離作用域;

7.1首先我們先來(lái)了解下scope的繼承機(jī)制。我們用ng-controller這個(gè)指令舉例,

[html] view plain copy 在CODE上查看代碼片<!DOCTYPE html>  <html lang="zh" ng-app="myApp">  <head>      <meta charset="UTF-8">      <title>AngularJS入門學(xué)習(xí)</title>      <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  </head>  <body>  <div ng-controller='MainController'>          父親:{{name}}<input ng-model="name" />          <div my-directive></div>    </div>  </body>  <script type="text/javascript">  var app = angular.module('myApp', []);  app.controller('MainController', function ($scope) {             $scope.name = '林炳文';  });  app.directive('myDirective', function () {              return {                  restrict: 'EA',                  scope:false,                  template: '<div>兒子:{{ name }}<input ng-model="name"/></div>'              };  });  </script>  </html>  

接下來(lái)我們通過(guò)一個(gè)簡(jiǎn)單明了的例子來(lái)說(shuō)明scope取值不同的差別:

scope:false

scope:true

scope:{}

當(dāng)為false時(shí)候,兒子繼承父親的值,改變父親的值,兒子的值也隨之變化,反之亦如此。(繼承不隔離)

當(dāng)為true時(shí)候,兒子繼承父親的值,改變父親的值,兒子的值隨之變化,但是改變兒子的值,父親的值不變。(繼承隔離)

當(dāng)為{}時(shí)候,沒(méi)有繼承父親的值,所以兒子的值為空,改變?nèi)魏我环降?#20540;均不能影響另一方的值。(不繼承隔離)

tip:當(dāng)你想要?jiǎng)?chuàng)建一個(gè)可重用的組件時(shí)隔離作用域是一個(gè)很好的選擇,通過(guò)隔離作用域我們確保指令是‘獨(dú)立’的,并可以輕松地插入到任何HTML app中,并且這種做法防止了父作用域被污染;7.2隔離作用域可以通過(guò)綁定策略來(lái)訪問(wèn)父作用域的屬性。

directive 在使用隔離 scope 的時(shí)候,提供了三種方法同隔離之外的地方交互。這三種分別是

@ 綁定一個(gè)局部 scope 屬性到當(dāng)前 dom 節(jié)點(diǎn)的屬性值。結(jié)果總是一個(gè)字符串,因?yàn)?dom 屬性是字符串。& 提供一種方式執(zhí)行一個(gè)表達(dá)式在父 scope 的上下文中。如果沒(méi)有指定 attr 名稱,則屬性名稱為相同的本地名稱。= 通過(guò) directive 的 attr 屬性的值在局部 scope 的屬性和父 scope 屬性名之間建立雙向綁定。

@ 局部 scope 屬性

@ 方式局部屬性用來(lái)訪問(wèn) directive 外部環(huán)境定義的字符串值,主要是通過(guò) directive 所在的標(biāo)簽屬性綁定外部字符串值。這種綁定是單向的,即父 scope 的綁定變化,directive 中的 scope 的屬性會(huì)同步變化,而隔離 scope 中的綁定變化,父 scope 是不知道的。

如下示例:directive 聲明未隔離 scope 類型,并且使用@綁定 name 屬性,在 directive 中使用 name 屬性綁定父 scope 中的屬性。當(dāng)改變父 scope 中屬性的值的時(shí)候,directive 會(huì)同步更新值,當(dāng)改變 directive 的 scope 的屬性值時(shí),父 scope 無(wú)法同步更新值。

js 代碼:

[html] view plain copy 在CODE上查看代碼片<!DOCTYPE html>  <html lang="zh" ng-app="myApp">  <head>      <meta charset="UTF-8">      <title>AngularJS入門學(xué)習(xí)</title>      <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  </head>  <body>  <div ng-controller="myController">     <div class="result">         <div>父scope:             <div>Say:{{name}}<br>改變父scope的name:<input type="text" value="" ng-model="name"/></div>         </div>         <div>隔離scope:             <div isolated-directive name="{{name}}"></div>         </div>          <div>隔離scope(不使用父scope {{name}}):               <div isolated-directive name="name"></div>           </div>     </div>  </body>  <script type="text/javascript">  var app = angular.module('myApp', []);   app.controller("myController", function ($scope) {          $scope.name = "hello world";      }).directive("isolatedDirective", function () {          return {              scope: {                  name: "@"              },              template: 'Say:{{name}} <br>改變隔離scope的name:<input type="buttom" value="" ng-model="name" class="ng-pristine ng-valid">'          };  });  </script>  </html>  結(jié)果:頁(yè)面初始效果

動(dòng)畫效果:

可以看到父scope上的內(nèi)容發(fā)生改變,子scope同時(shí)發(fā)生改變。而子scope上的內(nèi)容發(fā)生改變。不影響父scope上的內(nèi)容!

= 局部 scope 屬性

= 通過(guò) directive 的 attr 屬性的值在局部 scope 的屬性和父 scope 屬性名之間建立雙向綁定。意思是,當(dāng)你想要一個(gè)雙向綁定的屬性的時(shí)候,你可以使用=來(lái)引入外部屬性。無(wú)論是改變父 scope 還是隔離 scope 里的屬性,父 scope 和隔離 scope 都會(huì)同時(shí)更新屬性值,因?yàn)樗鼈兪请p向綁定的關(guān)系。

示例代碼:

[html] view plain copy 在CODE上查看代碼片<!DOCTYPE html>  <html lang="zh" ng-app="myApp">  <head>      <meta charset="UTF-8">      <title>AngularJS入門學(xué)習(xí)</title>      <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  </head>  <body>  <div ng-controller="myController">      <div>父scope:          <div>Say:{{userBase.name}}<br>改變父scope的name:<input type="text" value="" ng-model="userBase.name"/></div>      </div>      <div>隔離scope:          <div isolated-directive user="userBase"></div>      </div>  </div>  </body>  <script type="text/javascript">  var app = angular.module('myApp', []);   app.controller("myController", function ($scope) {          $scope.userBase = {              name: 'hello',              id: 1          };      }).directive("isolatedDirective", function () {          return {              scope: {                  user: "="              },              template: 'Say:{{user.name}} <br>改變隔離scope的name:<input type="buttom" value="" ng-model="user.name"/>'          }      })  </script>  </html>  效果:

可以看到父scope和子scope上的內(nèi)容一直都是一樣的!

& 局部 scope 屬性

& 方式提供一種途經(jīng)是 directive 能在父 scope 的上下文中執(zhí)行一個(gè)表達(dá)式。此表達(dá)式可以是一個(gè) function。比如當(dāng)你寫了一個(gè) directive,當(dāng)用戶點(diǎn)擊按鈕時(shí),directive 想要通知 controller,controller 無(wú)法知道 directive 中發(fā)生了什么,也許你可以通過(guò)使用 angular 中的 event 廣播來(lái)做到,但是必須要在 controller 中增加一個(gè)事件監(jiān)聽(tīng)方法。最好的方法就是讓 directive 可以通過(guò)一個(gè)父 scope 中的 function,當(dāng) directive 中有什么動(dòng)作需要更新到父 scope 中的時(shí)候,可以在父 scope 上下文中執(zhí)行一段代碼或者一個(gè)函數(shù)。

如下示例在 directive 中執(zhí)行父 scope 的 function。

[html] view plain copy 在CODE上查看代碼片<!DOCTYPE html>  <html lang="zh" ng-app="myApp">  <head>      <meta charset="UTF-8">      <title>AngularJS入門學(xué)習(xí)</title>      <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  </head>  <body>   <div  ng-controller="myController">          <div>父scope:              <div>Say:{{value}}</div>          </div>          <div>隔離scope:              <div isolated-directive action="click()"></div>          </div>  </div>  </body>  <script type="text/javascript">  var app = angular.module('myApp', []);   app.controller("myController", function ($scope) {          $scope.value = "hello world";          $scope.click = function () {              $scope.value = Math.random();          };      }).directive("isolatedDirective", function () {          return {              scope: {                  action: "&"              },              template: '<input type="button" value="在directive中執(zhí)行父scope定義的方法" ng-click="action()"/>'          }      })  </script>  </html>  效果:

指令的內(nèi)容比較多,下一章節(jié)再來(lái)講講transclude、compline、link、contrller.下文見(jiàn)此跟我學(xué)AngularJs:Directive指令用法解讀(下)
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 朝阳县| 承德县| 尚义县| 萨迦县| 公安县| 潞城市| 平远县| 瑞安市| 蓬莱市| 井研县| 高邑县| 惠州市| 周宁县| 韶山市| 榆林市| 内黄县| 边坝县| 土默特左旗| 长治县| 阜新市| 大渡口区| 芮城县| 建昌县| 秦皇岛市| 樟树市| 茌平县| 靖西县| 澄迈县| 孝感市| 增城市| 襄城县| 高淳县| 吉林市| 曲松县| 青冈县| 中宁县| 富裕县| 文安县| 喀喇沁旗| 武陟县| 朝阳市|