ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 第八章 指令简介 调用指令意味着执行指令背后与之相关联的 JavaScript 代码,这些代码是我们用指令定义写出来的。 ### 作用 * 监视数据模型的变化. * 可以将数据模型的变化通知整个应用,甚至是系统外的组件. * 可以嵌套,隔离业务功能和数据. * 给表达式提供运算时所需的执行环境. ### 声明方式 声明指令本质上是在HTML中通过元素(E)、属性(A)、类(C)或注释(M)来添加功能。 ```html <my-directive>元素 element</my-directive> <div my-directive>属性 attribute</div> <div class="my-directive">类 class</div> <!-- directive:my-directive --> <!--注释 comment--> ``` ```javascript angular.module('myApp',[]) .directive('myDirective', function() { return { restrict: 'E', template: '<a href="http://google.com">Click me to go to Google</a>' }; }); ```   **通过**AngularJS模块API中的`.directive()`**方法**,我们可以通过传入一个字符串和一个函数来**注册**一个新**指令**。   其中字符串是这个指令的名字,指令名应该是驼峰命名风格的,函数应该返回一个对象。   **内置指令** 在AngularJS内部的指令。所有内置指令的命名空间都使用 **ng** 作为前缀。为了**防止命名空间冲突,不要在自定义指令前加ng前缀**。      **声明指令**本质上是在HTML中通过 **元素**(E)、**类**(C)、**注释**(M) 或 **属性**(A) 来添加功能。      我们坚持使用 **属性** 方式,因为它有比较好的跨浏览器兼容性。      注意每个浏览器的内置样式,以便决定指令模板在HTML中是嵌套在声明元素内,还是替换声明元素。    #### 用表达式来声明指令 ```html <my-directive="someExpression"> </my-directive> <div my-directive="someExpression"> </div> <div class="my-directive:someExpression"> </div> <!-- directive: my-directive someExpression --> ``` #### 作用域 ```html <!DOCTYPE html> <html ng-app="myApp"> <head> <title>Simple app</title> <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"> <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap-theme.css" rel="stylesheet"> <script src="angular.min.js"></script> </head> <body> {{child}} <input type="text" name="child" ng-model="child" /> <div ng-controller="ParentCtrl"> {{child}} <input type="text" name="child" ng-model="child" /> <div ng-controller="ChildCtrl"> {{child}} <input type="text" name="child" ng-model="child" /> </div> </div> <script type="text/javascript"> angular.module('myApp',[]) .run(function($rootScope){ $rootScope.child = 'root'; }) .controller('ParentCtrl', function($scope){ $scope.child = 'parent'; }) .controller('ChildCtrl', function($scope){ $scope.child = 'child'; }); </script> </body> </html> ```    ### 向指令中传递数据 ```html <div my-directive some-attr="someProperty with @ binding"></div> ``` ```javascript scope: { someProperty: '@someAttr' } ``` > 示例 ```html <!DOCTYPE html> <html ng-app="myApp"> <head> <title>Simple app</title> <meta charset="UTF-8"> <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"> <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap-theme.css" rel="stylesheet"> <script src="angular.min.js"></script> </head> <body> <div my-directive my-uri="http://google.com" my-link-text="{{user.name}}"></div> <script type="text/javascript"> angular.module('myApp',[]) .directive('myDirective', function(){ return { restrict : 'A', replace : true, scope : { myUrl : '@myUri', myLinkText : '@' }, template: '<a href="{{ myUrl }}">{{ myLinkText }}</a>' }; }); </script> </body> </html> ```