Angular1.x復雜指令實例詳解
本文實例講述了Angular1.x復雜指令。分享給大家供大家參考,具體如下:
.directive('unorderedList', function () { return { link: function (scope, element, attrs) { var data = scope[attrs['unorderedList'] || attrs['listSource'] ]; var propertyName = attrs['listProperty'] || "price || currency"; if(angular.isArray(data)){ var listElem = angular.element("<ul>"); if(element[0].nodeName == "#comment"){ element.parent().append(listElem); }else{ element.append(listElem); } for(var i=0, len=data.length; i<len; i++){ var itemElem = angular.element('<li>').text(scope.$eval(propertyName, data[i])); listElem.append(itemElem); } } }, restrict:'EACM' }; });
如何使用指令
當作元素使用(E)
<unordered-list list-source="products" list-property="price | currency" />
當unordered-list當作元素使用,需要添加另外的屬性代替unordered-list屬性的作用。
var data = scope[attrs['unorderedList'] || attrs['listSource'] ];
當作屬性使用(A)
<div unordered-list="products" list-property="price | currency"></div>
當作類的屬性值使用(C)
<div class="unordered-list: products" list-property="price | currency"></div>
當作注釋使用(M)
<!-- directive: unordered-list products -->
使用模板指令
.directive('unorderedList', function () { return { link: function (scope, element, attrs) { scope.data = scope[attrs['unorderedList']]; }, restrict: 'A', template:"<ul><li ng-repeat='item in data'>{{item.price | currency}}</li></ul>" }; });
使用函數作為模板
template屬性除了使用字符串,也可以指定一個函數來生成模板化的內容。該函數傳入兩個函數(指令所應用到的元素以及屬性集合)并返回將被插入到文檔中的HTML代碼片段。
<script type="text/javascript" id="listTemplate"> <ul> <li ng-repeat="item in data">{{item.price | currency}}</li> </ul> </script> <script> var myApp = angular.module('myApp', []) .controller('myCtrl', ["$scope", function ($scope) { $scope.products = [ { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 }, { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 }, { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 } ]; }]) .directive('unorderedList', function () { return { link: function (scope, element, attrs) { scope.data = scope[attrs['unorderedList']]; }, restrict: 'A', template:function () { return angular.element( document.querySelector("#listTemplate") ).html(); } }; }); </script>
使用外部模板
itemTemplate.html
<p>This is the form the template file</p> <ul> <li ng-repeat="item in data">{{item.price | currency}}</li> </ul>
.directive('unorderedList', function () { return { link: function (scope, element, attrs) { scope.data = scope[attrs['unorderedList']]; }, restrict: 'A', templateUrl:"itemTemplate.html" }; });
通過函數選擇一個外部模版
tableTemplate.html
<table> <thead> <tr> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> <tr ng-repeat="item in data"> <td>{{item.name}}</td> <td>{{item.price | currency}}</td> </tr> </tbody> </table>
<div unordered-list="products" template="table" class="table table-striped"> This is where the list will go </div>
.directive('unorderedList', function () { return { link: function (scope, element, attrs) { scope.data = scope[attrs['unorderedList']]; }, restrict: 'A', templateUrl: function (elem, attrs) { return attrs['template'] == "table" ? "tableTemplate.html" : "itemTemplate.html"; } }; });
table-striped樣式并沒有起作用,設置replace屬性為true后的效果是模版內容將替換掉指令所應用到的div元素。
管理指令的作用域
為每個指令實例創(chuàng)建自己的作用域
設置scope屬性為true將允許我們在同一個控制器里復用這個指令,可以避免指令共享數據值。
<div class="panel panel-default"> <div class="panel-body" scope-demo></div> <div class="panel-body" scope-demo></div> </div>
var myApp = angular.module('myApp', []) .controller('myCtrl', ["$scope", function ($scope) { $scope.data = {name:"Staven"}; $scope.city = "China" }]) .directive('scopeDemo', function () { return { template: function () { return angular.element(document.querySelector("#scopeTemplate")).html(); }, scope:true }; });
data.name這個屬性是在一個對象上定義的,意味著這個值將會在指令的哥哥實例之間所共享,而且所有相應的視圖會同步更新。
city是直接在控制器的作用于上被直接賦值的,意味著這個值只在此指令的作用域上有效。
創(chuàng)建隔離的作用域
對于在一個對象上定義的屬性,可能會被其他人改變。解決方法就是創(chuàng)建一個隔離的作用域,就是Angularjs為指令的每個實例創(chuàng)建一個獨立的作用域的地方,但是這個作用域并不繼承自控制器的作用域。當scope定義屬性被設置為一個對象時,可創(chuàng)建一個隔離的作用域。隔離的作用域的最基本類型是用一個沒有屬性的對象表示。
.directive('scopeDemo', function () { return { template: function () { return angular.element(document.querySelector("#scopeTemplate")).html(); }, scope:{} }; });
當創(chuàng)建在不同情況下復用的指令時,隔離的作用域是一種重要的構件時。因為它防止了在控制器作用域和指令之間出現了意料外的交互。但是完全隔絕一個指令會使得難以輸入和輸出數據。
隔絕的作用域允許使用應用于指令旁邊的元素上的屬性將數據值綁定到控制器作用域上。
單向綁定@:
向以@為前綴的作用域對象上增添一個屬性,以在一個隔離的作用力創(chuàng)建一個單向綁定。
<body ng-app="myApp" ng-controller="myCtrl"> <div class="panel panel-default"> <div class="panel-body"> Direct Binding:<input ng-model="data.name" /> </div> <div class="panel-body" scope-demo nameprop="{{data.name}}"></div> </div> </body> <script type="text/ng-template" id="scopeTemplate"> <div class="panel-body"> <p>Data Value:{{local}}</p> </div> </script> <script> var myApp = angular.module('myApp', []) .controller('myCtrl', ["$scope", function ($scope) { $scope.data = {name:"staven"}; }]) .directive('scopeDemo', function () { return { template: function () { return angular.element(document.querySelector("#scopeTemplate")).html(); }, scope:{ local:"@nameprop" } }; }); </script>
local屬性的值以@為前綴,制定了屬性local的值應該從一個來自名為nameprop的特性的單向綁定來獲得。
使用一個隔離的作用域使得指令不會繼承控制器作用域中的數據。
雙向綁定=:
向以=為前綴的作用域對象上增添一個屬性,以在一個隔離的作用域里創(chuàng)建一個雙向綁定。
在隔離作用于上的單向綁定總是被計算作字符串值,如果想訪問一個數組,就必須使用雙向綁定。
<div class="panel panel-default"> <div class="panel-body"> Direct Binding:<input ng-model="data.name" /> </div> <div class="panel-body" scope-demo nameprop="data.name"></div> </div> <script type="text/ng-template" id="scopeTemplate"> <div class="panel-body"> <p>Data Value:<input ng-model="local" /></p> </div> </script> <script> scope:{ local:"=nameprop" } </script>
使用單向綁定時,提供了一個被"{{"和"}}"字符所包圍的綁定表達式,但是angularjs需要知道在雙向綁定中哪個屬性需要被更新,所以不需要被"{{"和"}}"包圍。
計算表達式&:
向以&為前綴的作用域對象上增添一個屬性,在父作用域的上下文計算一個表達式。
<body ng-app="myApp" ng-controller="myCtrl"> <div class="panel panel-default"> <div class="panel-body"> Direct Binding:<input ng-model="data.name" /> </div> <div class="panel-body" scope-demo city="getCity(data.name)" nameprop="data.name"></div> </div> </body> <script type="text/ng-template" id="scopeTemplate"> <div class="panel-body"> <p>Name:{{local}}, City:{{cityFn()}}</p> </div> </script> <script> var myApp = angular.module('myApp', []) .controller('myCtrl', ["$scope", function ($scope) { $scope.data = {name:"staven",defaultCity:"hefei"}; $scope.getCity = function (name) { console.log(1); return name == 'staven' ? $scope.data.defaultCity : "Unknown"; } }]) .directive('scopeDemo', function () { return { template: function () { return angular.element(document.querySelector("#scopeTemplate")).html(); }, scope:{ local:"=nameprop", cityFn:"&city" } }; }); </script>
調用cityFn()時,使用了圓括號,要計算被這個特性所指定的表達式,這是必需的,即使當表達式本身就是一個函數調用時。
使用隔離作用域的數據來計算一個表達式
可以將來自代計算的隔離作用域的數據為控制器作用域表達式的一部分。
<div class="panel-body" scope-demo city="getCity(nameVal)" nameprop="data.name"></div> <script type="text/ng-template" id="scopeTemplate"> <div class="panel-body"> <p>Name:{{local}}, City:{{cityFn({nameVal: local})}}</p> </div> </script>
更多關于AngularJS相關內容感興趣的讀者可查看本站專題:《AngularJS指令操作技巧總結》、《AngularJS入門與進階教程》及《AngularJS MVC架構總結》
希望本文所述對大家AngularJS程序設計有所幫助。
相關文章
AngularJS中$injector、$rootScope和$scope的概念和關聯關系深入分析
這篇文章主要介紹了AngularJS中$injector、$rootScope和$scope的概念和關聯關系,結合實例形式較為深入的分析了$injector、$rootScope和$scope的概念、功能、使用方法及相互之間的關系,需要的朋友可以參考下2017-01-01Angular.js回顧ng-app和ng-model使用技巧
這篇文章主要回顧Angular.js中ng-app和ng-model使用技巧,感興趣的小伙伴們可以參考一下2016-04-04