AngularJS 自定义指令directive 介绍

时间:2023-03-10 00:19:55
AngularJS 自定义指令directive 介绍

AngularJS 自定义指令directive 介绍

---------------------------------------------------------------------------

指令的作用是把我们自定义的语义化标签替换成浏览器能够认识的HTML标签

指令

link: function (scope, element, attrs, accordionController) {

(1)$scope,与指令元素相关联的作用域

(2)$element,当前元素 ,例如<p> 元素//从元素列表中获取元素,并绑定相应的事件

(3)$attrs,由当前元素的属性对象

(4)$transclude,嵌入链接函数,实际被执行用来克隆元素和操作DOM的函数

举例如下,你可以进行对照理解:

 var expModule=angular.module('expanderModule',[])
expModule.directive('accordion', function() {
return {
restrict : 'EA',
replace : true,
transclude : true,
template : '<div ng-transclude></div>',
controller : function() {
var expanders = [];
this.gotOpened = function(selectedExpander) {
angular.forEach(expanders, function(expander) {
if (selectedExpander != expander) {
expander.showMe = false;
}
});
}
this.addExpander = function(expander) {
expanders.push(expander);
}
}
}
});

--------------------------------------------------------------------------------------------------------------

AngularJS 自定义指令directive 介绍

如果还是不太能理解可以看这个链接,这里比较详细,也写的不错http://blog.****.net/kongjiea/article/details/49840035