一:自定義指令常用模板
下面是大致的說明,不是全面的,后面來具體說明一些沒有提及的細節和重要的相關知識:
angular.module('yelloxingApp', []).directive('uiDirective', function() { return { restrict:String,//標明該指令可以在模板中用于元素E、屬性A、類C和注釋M或組合 priority:Number,//設置指令執行優先級,在某個DOM上優先級高的會先執行 terminal:Boolean, template:String or Template Function,//就是設置模板,和下面的templateUrl屬性二個只可以設置一個,目的一樣 templateUrl:String or Template Function,//除了字符串,這二個屬性還可以設置函數 replace:Boolean,//指令模板是否替換原來的元素 scope:Boolean or Object, controller:String or function(scope, element, attrs) { ... }, require:String or Array, //你需要知道link在每個實例都執行一遍,compile全程只會執行一遍 link: function(scope, element, attrs,ctrl) { ... }, compile:function(element, attrs) { //常用的就是compile的此處寫執行一次的代碼,或者在link方法里面寫和dom有關的操作 } };}); 二:一些屬性說明
【scope】
可以設置boolean或者對象,先來說說boolean,這個比較簡單:
1.當設置true的時候,表示繼承父scope,是一個子scope;
2.當設置false的時候,直接使用父scope。
還有一種對象設置方法,就是設置一種隔離的scope,在使用隔離scope的時候,提供了三種方法同隔離之外的地方交互,下面用一個例子來一一說明:
angular.module('yelloxingApp', []).directive("scopeExample", ['$rootScope', function($rootScope) { return { restrict: 'A', scope: { _userDataName: "=userDataName", _onSend: "&onSend", _fromName: "@fromName" }, template: ` <button ng-click="_useParentMethod()"> 點擊按鈕調用父級的方法 </button> <input ng-model="_userDataName"/> <ul> <li>fromName={{newfromname}}</li> <li>這是從父級獲取到的{{_userDataName}}</li> </ul>`, link: function($scope, element, attrs) { //使用@符號可將本地作用域的變量與DOM屬性的值進行綁定,即這里通過@得到父類fromName的值 $scope.newfromname = $scope._fromName; $scope._useParentMethod = function() { //使用&符號可以在其中調用父類的方法 $scope._onSend({ "email": { "email": "yelloxing@gmail.com" } }); console.log($scope._userDataName); }; } };}]);上面是指令的寫法,下面來看看控制器里面有什么:
$scope.name = "心葉";$scope.user = "yelloxing";$scope.sendMail = function(email){ console.error(email);}
新聞熱點
疑難解答
圖片精選