@father:<input type="text" ng-model="data"/> <me title="{{data}}">@</me> =father:<input type="text" ng-model="msg"/> <you title="msg">=</you> <he func="cli(str)">&</he>
接下来是主要的js代码:
1 var app = angular.module("myApp", []); 2 app.controller('myCtrl',['$scope',function($scope) { 3 $scope.cli = function(str) { 4 console.log(str); 5 } 6 // $scope.str = "this is he!"; 7 }]) 8 app.directive('me',function() { 9 return { 10 restrict:"E", 11 scope:{ 12 title:'@' 13 }, 14 template:"<div>{{title}}@:<input type='text' ng-model='title'/></div>" 15 } 16 }) 17 18 19 app.directive('you',function() { 20 return { 21 restrict:"E", 22 scope: { 23 title:"=" 24 }, 25 template:"<div>{{title}}=:<input type='text' ng-model='title'/></div>" 26 } 27 }) 28 29 app.directive('he',function() { 30 return { 31 restrict:"E", 32 scope: { 33 func:"&" 34 }, 35 template:"<div><input ng-model='v'/><button ng-click='func({str:v})'>点击</button></div>"//在func里面加参数的写法 36 } 37 })
总结:@就是在引用时要加{{}},且子元素不能改变父元素的model,=就是在引用时直接引用,不加{{}},子元素可以改变父元素的model,双向绑定,&是负责方法调用的,其中可以添加参数,如以上例子所示写法。