自定義屬性的四種類別
分為: 元素E,屬性A,注釋M,類C , 分別如下:
<my-dir></my-dir> <span my-dir="exp"></span> <!-- directive: my-dir exp --> <span class="my-dir: exp;"></span>
簡單創建一個指令
html結構:
<div ng-controller="myCtrl"> <div my-customer></div></div>
JavaScript結構:
angular.module('myApp', []) .controller('myCtrl', ['$scope', function($scope) { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) .directive('myCustomer', function() { return { template: 'Name: {{customer.name}} Address: {{customer.address}}' }; });輸出:
Name: Naomi Address: 1600 Amphitheatre
說明: 此處,myCtrl 中定義的 $scope.customer 屬性和屬性值都在指令中的模板使用了。同樣的,在指令return 對象中的 template 也可被替換成一路徑,在路徑html中書寫和template中同樣的代碼,使用這種方式,可以操作更多代碼。
templateUrl 函數式編程
html結構:
<div ng-controller="myCtrl"> <div my-customer></div></div>
javascript結構:
angular.module('myApp', []) .controller('myCtrl', ['$scope', function($scope) { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) .directive('myCustomer', function() { return { templateUrl: function(elem, attr) { return 'customer-' + attr.type + '.html'; } }; });不同的templateUrl ①
Name: {{customer.name}}不同的templateUrl ②
Address: {{customer.address}}輸出結果:
Name: Naomi
Address: 1600 Amphitheatre
說明: templateUrl 的值可以是一個函數返回值,返回用于指令中的html模板的url。
隔離指令的作用域
① 通過不同的controller
html結構:
<div ng-app="myApp"> <div ng-controller="myCtrl1"> <my-customer></my-customer> </div> <div ng-controller="myCtrl2"> <my-customer></my-customer> </div></div>
javascript結構:
angular.module('myApp', []) .controller('myCtrl1', ['$scope', function($scope) { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) .controller('myCtrl2', ['$scope', function($scope) { $scope.customer = { name: 'Igor', address: '123 Somewhere' }; }]) .directive('myCustomer', function() { return { restrict: 'E', templateUrl: 'my-customer.html' }; });templateUrl html 結構:
Name: {{customer.name}} Address: {{customer.address}}
新聞熱點
疑難解答
圖片精選