1 <!DOCTYPE html> 2 <html ng-app="app"> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <script type="text/javascript" src="../js/angular-1.2.16.js" ></script> 7 </head> 8 <body ng-controller="dirCtr"> 9 <input type="text" ng-model="myUrl" /> 10 <div my-directive some-attr="{{myUrl}}" my-link-text="click here"></div> 11 </body> 12 <script type="text/javascript"> 13 var app=angular.module("app",[]); 14 app.directive("myDirective",function(){ 15 return{ 16 restrict:"A", 17 replace:true, 18 scope:{ 19 myUrl:'@someAttr', 20 myLinkText:'@myLinkText1' 21 }, 22 template:'<div><input type="text" ng-model="myUrl" /><a href="{{myUrl}}">{{myUrl}}</a></div>' 23 24 }; 25 }); 26 app.controller("dirCtr",function($scope){ 27 $scope.myLinkText="baidu"; 28 }); 29 </script> 30 </html>
当你改变上面的输入框时,下面的输入框跟着变,但是当你改变下面的输入框时,上面的输入框不跟真变.
原因是参数scope造成了了指令的一个局部区域.
那么怎么才能输入下面的文本框,上面的也跟着变呢.
看下面的代码.
1 <!DOCTYPE html> 2 <html ng-app="app"> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <script type="text/javascript" src="../js/angular-1.2.16.js" ></script> 7 </head> 8 <body> 9 <input type="text" ng-model="theirUrl" /> 10 <div my-directive some-attr="theirUrl" my-link-text="click here"></div> 11 </body> 12 <script type="text/javascript"> 13 var app=angular.module("app",[]); 14 app.directive("myDirective",function(){ 15 return{ 16 restrict:"A", 17 replace:true, 18 scope:{ 19 myUrl:'=someAttr', 20 myLinkText:'@' 21 }, 22 template:'<div><input type="text" ng-model="myUrl" /><a href="{{myUrl}}">{{myUrl}}</a></div>' 23 24 }; 25 }); 26 </script> 27 </html>
帅呆了,酷毙的双向绑定.