首页 > 语言 > JavaScript > 正文

详解angular 中的自定义指令之详解API

2024-05-06 15:15:39
字体:
来源:转载
供稿:网友

自定义属性的四种类别

分为: 元素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}}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选