跟我学AngularJs:Directive指令用法解读(上)

来源:互联网 发布:mapreduce编程语言 编辑:程序博客网 时间:2024/05/16 15:44

 林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka

本教程使用AngularJS版本:1.5.3

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

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

       摘要: Directive(指令)笔者认为是AngularJ非常强大而有有用的功能之一。它就相当于为我们写了公共的自定义DOM元素或CLASS属性或ATTR属性,并且它不只是单单如此,你还可以在它的基础上来操作scope、绑定事件、更改样式等。通过这个Directive,我们可以封装很多公共指令,比如分页指令、自动补全指令等等。然后在HTML页面里只需要简单的写一行代码就可以实现很多强大的功能。一般情况下,需要用Directive有下面的情景:

1. 使你的Html更具语义化,不需要深入研究代码和逻辑即可知道页面的大致逻辑。
2. 抽象一个自定义组件,在其他地方进行重用。

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

AngularJs的指令定义大致如下

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. angular.module("app",[]).directive("directiveName",function(){  
  2.     return{  
  3.      //通过设置项来定义  
  4.     };  
  5. })  

Directive可以放置于元素名、属性、class、注释中。下面是引用myDir这个directive的等价方式。(但很多directive都限制为“属性”的使用方式)

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <span <span style="font-family: Arial, Helvetica, sans-serif;">directive-name</span><span style="font-family: Arial, Helvetica, sans-serif;">="exp"></span>//属性</span>  
  2.   
  3. <span class="<span style="font-family: Arial, Helvetica, sans-serif;">directive-name</span>: exp;"></span>//class  
  4.   
  5. <<span style="font-family: Arial, Helvetica, sans-serif;">directive-name</span>></<span style="font-family: Arial, Helvetica, sans-serif;">directive-name</span>>//元素  
  6.   
  7. <!-- directive: <span style="font-family: Arial, Helvetica, sans-serif;">directive-name </span><span style="font-family: Arial, Helvetica, sans-serif;">exp -->//注释</span>  

如下一个实例 :

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS入门学习</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <hello-world></hello-world>  
  10. </body>  
  11. <script type="text/javascript">  
  12. var app = angular.module('myApp', []);  
  13. app.directive('helloWorld', function() {  
  14.     return {  
  15.         restrict: 'E',  
  16.         template: '<div>Hi 我是林炳文~~~</div>',  
  17.         replace: true  
  18.     };  
  19. });  
  20. </script>  
  21. </html>  
结果:


下面是一个directive的详细版

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. var myModule = angular.module(...);  
  2.   
  3. myModule.directive('directiveName', function factory(injectables) {  
  4.   
  5.  var directiveDefinitionObject = {  
  6.   
  7.    priority: 0,  
  8.   
  9.    template: '<div></div>',  
  10.   
  11.    templateUrl: 'directive.html',  
  12.   
  13.    replace: false,  
  14.   
  15.    transclude: false,  
  16.   
  17.    restrict: 'A',  
  18.   
  19.    scope: false,  
  20.   
  21.    compile: function compile(tElement, tAttrs, transclude) {  
  22.   
  23.      return {  
  24.   
  25.        pre: function preLink(scope, iElement, iAttrs, controller) { ... },  
  26.   
  27.        post: function postLink(scope, iElement, iAttrs, controller) { ... }  
  28.   
  29.     }  
  30.   
  31.   },  
  32.   
  33.    link: function postLink(scope, iElement, iAttrs) { ... }  
  34.   
  35. };  
  36.   
  37.  return directiveDefinitionObject;  
  38.   
  39. });  

二、Directive指令内容解读

可 以看到它有8个内容

1.restrict
(字符串)可选参数,指明指令在DOM里面以什么形式被声明;取值有:E(元素),A(属性),C(类),M(注释),其中默认值为A;当然也可以两个一起用,比如EA.表示即可以是元素也可以是属性。
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. E(元素):<directiveName></directiveName>  
  2. A(属性):<div directiveName='expression'></div>  
  3. C(类): <div class='directiveName'></div>  
  4. M(注释):<--directive:directiveName expression-->  

一般情况下E/A/C用得比较多。
2.priority
(数字),可选参数,指明指令的优先级,若在单个DOM上有多个指令,则优先级高的先执行;

3.terminal
(布尔型),可选参数,可以被设置为true或false,若设置为true,则优先级低于此指令的其他指令则无效,不会被调用(优先级相同的还是会执行)

4.template(字符串或者函数)可选参数,可以是:
(1)一段HTML文本
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS入门学习</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <hello-world></hello-world>  
  10. </body>  
  11. <script type="text/javascript">  
  12. var app = angular.module('myApp', []);  
  13. app.directive('helloWorld', function() {  
  14.     return {  
  15.         restrict: 'E',  
  16.         template: '<div><h1>Hi 我是林炳文~~~</h1></div>',  
  17.         replace: true  
  18.     };  
  19. });  
  20. </script>  
  21. </html>  


(2)一个函数,可接受两个参数tElement和tAttrs
其中tElement是指使用此指令的元素,而tAttrs则实例的属性,它是一个由元素上所有的属性组成的集合(对象)形如:
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <hello-world2 title = '我是第二个directive'></hello-world2>  

其中title就是tattrs上的属性

下面让我们看看template是一个函数时候的情况

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS入门学习</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <hello-world></hello-world>  
  10. <hello-world2 title = '我是第二个directive'></hello-world2>  
  11. </body>  
  12. <script type="text/javascript">  
  13. var app = angular.module('myApp', []);  
  14. app.directive('helloWorld', function() {  
  15.     return {  
  16.         restrict: 'E',  
  17.         template: '<div><h1>Hi 我是林炳文~~~</h1></div>',  
  18.         replace: true  
  19.     };  
  20. });  
  21. app.directive("helloWorld2",function(){  
  22.                 return{  
  23.                  restrict:'EAC',  
  24.                  template: function(tElement,tAttrs){  
  25.                     var _html = '';  
  26.                     _html += '<div>' +'hello '+tAttrs.title+'</div>';  
  27.                     return _html;  
  28.                  }  
  29.      };  
  30.  });  
  31. </script>  
  32. </html>  
结果:


可以看到指令中还用到了hello-world2中的标签中的 title字段

5.templateUrl(字符串或者函数),可选参数,可以是

(1)一个代表HTML文件路径的字符串

(2)一个函数,可接受两个参数tElement和tAttrs(大致同上)

注意:在本地开发时候,需要运行一个服务器,不然使用templateUrl会报错 Cross Origin Request Script(CORS)错误。由于加载html模板是通过异步加载的,若加载大量的模板会拖慢网站的速度,这里有个技巧,就是先缓存模板

你可以再你的index页面加载好的,将下列代码作为你页面的一部分包含在里面。

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

这里的id属性就是被设置在templateUrl上用的。

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS入门学习</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <hello-world></hello-world>  
  10. </body>  
  11. <script type="text/javascript">  
  12. var app = angular.module('myApp', []);  
  13. app.directive('helloWorld', function() {  
  14.     return {  
  15.         restrict: 'E',  
  16.         templateUrl: 'hello.html',  
  17.         replace: true  
  18.     };  
  19. });  
  20. </script>  
  21. <script type='text/ng-template' id='hello.html'>  
  22.           <div><h1>Hi 我是林炳文~~~</h1></div>  
  23. </script>  
  24. </html>  

输出结果:


另一种办法缓存是:

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. app.run(["$templateCache", function($templateCache) {  
  2.   $templateCache.put("hello.html",  
  3.     "<div><h1>Hi 我是林炳文~~~</h1></div>");  
  4. }]);  

使用实例如下:

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS入门学习</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <hello-world></hello-world>  
  10. </body>  
  11. <script type="text/javascript">  
  12. var app = angular.module('myApp', []);  
  13. app.directive('helloWorld', function() {  
  14.     return {  
  15.         restrict: 'E',  
  16.         templateUrl: 'hello.html',  
  17.         replace: true  
  18.     };  
  19. });  
  20. app.run(["$templateCache", function($templateCache) {  
  21.   $templateCache.put("hello.html",  
  22.     "<div><h1>Hi 我是林炳文~~~</h1></div>");  
  23. }]);  
  24. </script>  
  25. </html>  

结果:


 其实第一种方法还好一些,写起来会比较快,笔者就得最多的也是第一种写法,直接包在scprit当中

 6.replace

(布尔值),默认值为false,设置为true时候,我们再来看看下面的例子(对比下在template时候举的例子)

                 

 replace为true时,hello-world这个标签不在了,反之,则存在。

7.scope

(1)默认值false。表示继承父作用域;

(2)true。表示继承父作用域,并创建自己的作用域(子作用域);

(3){}。表示创建一个全新的隔离作用域;

7.1首先我们先来了解下scope的继承机制。我们用ng-controller这个指令举例,

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS入门学习</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <div ng-controller='MainController'>  
  10.         父亲:{{name}}<input ng-model="name" />  
  11.         <div my-directive></div>  
  12.   </div>  
  13. </body>  
  14. <script type="text/javascript">  
  15. var app = angular.module('myApp', []);  
  16. app.controller('MainController', function ($scope) {  
  17.            $scope.name = '林炳文';  
  18. });  
  19. app.directive('myDirective', function () {  
  20.             return {  
  21.                 restrict: 'EA',  
  22.                 scope:false,  
  23.                 template: '<div>儿子:{{ name }}<input ng-model="name"/></div>'  
  24.             };  
  25. });  
  26. </script>  
  27. </html>  

接下来我们通过一个简单明了的例子来说明scope取值不同的差别:

scope:false


scope:true


scope:{}


当为false时候,儿子继承父亲的值,改变父亲的值,儿子的值也随之变化,反之亦如此。(继承不隔离)

当为true时候,儿子继承父亲的值,改变父亲的值,儿子的值随之变化,但是改变儿子的值,父亲的值不变。(继承隔离)

当为{}时候,没有继承父亲的值,所以儿子的值为空,改变任何一方的值均不能影响另一方的值。(不继承隔离)

tip:当你想要创建一个可重用的组件时隔离作用域是一个很好的选择,通过隔离作用域我们确保指令是‘独立’的,并可以轻松地插入到任何HTML app中,并且这种做法防止了父作用域被污染;
7.2隔离作用域可以通过绑定策略来访问父作用域的属性。

directive 在使用隔离 scope 的时候,提供了三种方法同隔离之外的地方交互。这三种分别是

  • @ 绑定一个局部 scope 属性到当前 dom 节点的属性值。结果总是一个字符串,因为 dom 属性是字符串。
  • & 提供一种方式执行一个表达式在父 scope 的上下文中。如果没有指定 attr 名称,则属性名称为相同的本地名称。
  • = 通过 directive 的 attr 属性的值在局部 scope 的属性和父 scope 属性名之间建立双向绑定。

@ 局部 scope 属性

@ 方式局部属性用来访问 directive 外部环境定义的字符串值,主要是通过 directive 所在的标签属性绑定外部字符串值。这种绑定是单向的,即父 scope 的绑定变化,directive 中的 scope 的属性会同步变化,而隔离 scope 中的绑定变化,父 scope 是不知道的。

如下示例:directive 声明未隔离 scope 类型,并且使用@绑定 name 属性,在 directive 中使用 name 属性绑定父 scope 中的属性。当改变父 scope 中属性的值的时候,directive 会同步更新值,当改变 directive 的 scope 的属性值时,父 scope 无法同步更新值。

js 代码:

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS入门学习</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <div ng-controller="myController">  
  10.    <div class="result">  
  11.        <div>父scope:  
  12.            <div>Say:{{name}}<br>改变父scope的name:<input type="text" value="" ng-model="name"/></div>  
  13.        </div>  
  14.        <div>隔离scope:  
  15.            <div isolated-directive name="{{name}}"></div>  
  16.        </div>  
  17.         <div>隔离scope(不使用父scope {{name}}):  
  18.              <div isolated-directive name="name"></div>  
  19.          </div>  
  20.    </div>  
  21. </body>  
  22. <script type="text/javascript">  
  23. var app = angular.module('myApp', []);  
  24.  app.controller("myController", function ($scope) {  
  25.         $scope.name = "hello world";  
  26.     }).directive("isolatedDirective", function () {  
  27.         return {  
  28.             scope: {  
  29.                 name: "@"  
  30.             },  
  31.             template: 'Say:{{name}} <br>改变隔离scope的name:<input type="buttom" value="" ng-model="name" class="ng-pristine ng-valid">'  
  32.         };  
  33. });  
  34. </script>  
  35. </html>  
结果:页面初始效果

动画效果:


可以看到父scope上的内容发生改变,子scope同时发生改变。而子scope上的内容发生改变。不影响父scope上的内容!

= 局部 scope 属性

= 通过 directive 的 attr 属性的值在局部 scope 的属性和父 scope 属性名之间建立双向绑定。
意思是,当你想要一个双向绑定的属性的时候,你可以使用=来引入外部属性。无论是改变父 scope 还是隔离 scope 里的属性,父 scope 和隔离 scope 都会同时更新属性值,因为它们是双向绑定的关系。

示例代码:

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS入门学习</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <div ng-controller="myController">  
  10.     <div>父scope:  
  11.         <div>Say:{{userBase.name}}<br>改变父scope的name:<input type="text" value="" ng-model="userBase.name"/></div>  
  12.     </div>  
  13.     <div>隔离scope:  
  14.         <div isolated-directive user="userBase"></div>  
  15.     </div>  
  16. </div>  
  17. </body>  
  18. <script type="text/javascript">  
  19. var app = angular.module('myApp', []);  
  20.  app.controller("myController", function ($scope) {  
  21.         $scope.userBase = {  
  22.             name: 'hello',  
  23.             id: 1  
  24.         };  
  25.     }).directive("isolatedDirective", function () {  
  26.         return {  
  27.             scope: {  
  28.                 user: "="  
  29.             },  
  30.             template: 'Say:{{user.name}} <br>改变隔离scope的name:<input type="buttom" value="" ng-model="user.name"/>'  
  31.         }  
  32.     })  
  33. </script>  
  34. </html>  
效果:

可以看到父scope和子scope上的内容一直都是一样的!

& 局部 scope 属性

& 方式提供一种途经是 directive 能在父 scope 的上下文中执行一个表达式。此表达式可以是一个 function。
比如当你写了一个 directive,当用户点击按钮时,directive 想要通知 controller,controller 无法知道 directive 中发生了什么,也许你可以通过使用 angular 中的 event 广播来做到,但是必须要在 controller 中增加一个事件监听方法。
最好的方法就是让 directive 可以通过一个父 scope 中的 function,当 directive 中有什么动作需要更新到父 scope 中的时候,可以在父 scope 上下文中执行一段代码或者一个函数。

如下示例在 directive 中执行父 scope 的 function。

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS入门学习</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9.  <div  ng-controller="myController">  
  10.         <div>父scope:  
  11.             <div>Say:{{value}}</div>  
  12.         </div>  
  13.         <div>隔离scope:  
  14.             <div isolated-directive action="click()"></div>  
  15.         </div>  
  16. </div>  
  17. </body>  
  18. <script type="text/javascript">  
  19. var app = angular.module('myApp', []);  
  20.  app.controller("myController", function ($scope) {  
  21.         $scope.value = "hello world";  
  22.         $scope.click = function () {  
  23.             $scope.value = Math.random();  
  24.         };  
  25.     }).directive("isolatedDirective", function () {  
  26.         return {  
  27.             scope: {  
  28.                 action: "&"  
  29.             },  
  30.             template: '<input type="button" value="在directive中执行父scope定义的方法" ng-click="action()"/>'  
  31.         }  
  32.     })  
  33. </script>  
  34. </html>  
效果:


指令的内容比较多,下一章节再来讲讲transclude、compline、link、contrller.下文见此跟我学AngularJs:Directive指令用法解读(下)

0 0