这段时间在学习angularjs,对directive指令的绑定策略弄了好久才明白,现在做下笔记方便以后查阅,若有错误欢迎指出。
为了使新的指令作用域能访问当前的作用域的一些属性,通常会使用@、=、&三种方式进行绑定
1 <div ng-controller="ctrl"> 2 <test-dire name="taven" age="myAge" on-send="test(name)" on-call="test1({key2, key1})"></test-dire> 3 </div> 4 <script> 5 angular.module('myApp', ['test']) 6 .controller('ctrl', function($scope){ 7 $scope.name = 'hello world'; 8 $scope.myAge = 'three'; 9 $scope.test1 = function(obj){ 10 alert(JSON.stringify(obj)); // {"key2":"three","key1":"taven"} 11 }; 12 $scope.test = function(str){ 13 alert(str); //taven 14 }; 15 }); 16 17 angular.module('test', []) 18 .directive('testDire', function () { 19 return{ 20 restrict: 'ECMA', 21 replace: true, 22 template: '<div ng-click="onSend({name})" ng-mouseenter="onCall({key1:name,key2:age})">指令:@{{name}} , ={{age}}</div>', 23 scope: { 24 name: '@name', //绑定'test-dire'标签name属性值 (name='taven'),即绑定'taven' 25 age: '=age', //绑定当前作用域中属性名为'test-dire'标签age的属性值(age="myAge"),即绑定$scope.myAge 也就是 'three' 26 onCall: '&', //绑定'test-dire'标签on-send属性的test方法,并将当前指令绑定name和age值传递给该方法 27 onSend: '&' //将当前指令绑定name值传递给该方法 28 } 29 } 30 }); 31 32 </script>