引入主題背景:angular 的指令配置中的template可以直接使用硬編碼寫相應的代碼,不過也可以根據變量,進行動態更新。那么需要用到那些變量,因用法的不同,所以需要設置合適的綁定策略。
1:先說指令域scope的@
我覺得描述很費勁,直接用代碼來闡述:
AngularJS.html
<!doctype html> <html ng-app='myApp'> <head> </head> <body> <div ng-controller="listCtrl"> <input type="text" ng-model="t" /> <kid title="{{t}}" > //這個必須指定的,這里的title是指令里scope的@對應的,t就是控制域scope下的 <span>我的angularjs</span> </kid> </div> <script type="text/javascript" src="angular.js"></script> <script type="text/javascript" src="main05.js"></script> </body></html> main05.js
var myApp=angular.module('myApp',[]); myApp.controller('listCtrl',function($scope){ $scope.logchore="motorola"; }); myApp.directive('kid',function(){ return { 'restrict':'E', scope:{ title:"@" }, template:'<div >{{title}}</div>' } }); 在輸入框輸入數字會綁定到指令模板的title中。
2:再說說Scope的=
angularjs.html
<!doctype html> <html ng-app='myApp'> <head> </head> <body> <div ng-controller="listCtrl"> <input type="text" ng-model="t" /> <kid title="t" > //和上面相比,這個直接賦值等于scope域下的t了 <p>{{title}}</p> <span>我的angularjs</span> </kid> </div> <script type="text/javascript" src="angular.js"></script> <script type="text/javascript" src="main05.js"></script> </body></html> main05.js代碼如下:
var myApp=angular.module('myApp',[]); myApp.controller('listCtrl',function($scope){ $scope.logchore="motorola"; }); myApp.directive('kid',function(){ return { 'restrict':'E', scope:{ title:"=" }, template:'<div >{{title}}</div>' } }); 3:最后說&,這個是用來方法調用的
angularjs.html代碼如下:
<!doctype html> <html ng-app='myApp'> <head> </head> <body> <div ng-controller="listCtrl"> <kid flavor="logchore()" ></kid> //先比=,函數賦值的形式,而logchore函數必須是域scope下聲明的函數 </div> <script type="text/javascript" src="angular.js"></script> <script type="text/javascript" src="main05.js"></script> </body></html>
main05.js代碼如下:
var myApp=angular.module('myApp',[]); myApp.controller('listCtrl',function($scope){ $scope.logchore=function(){ alert('ok'); }; }); myApp.directive('kid',function(){ return { 'restrict':'E', scope:{ flavor:"&" }, template:'<div ><button ng-click="flavor()"></button></div>' } });
新聞熱點
疑難解答
圖片精選