0
此指令的用意是创建一个Select-All指令,该指令可以附加到任何类型的html元素以供重用。在AngularJS上不调用指令方法的动态元素
的CoffeeScript:
App.directive "selectAll", [ ->
restrict: 'A',
replace : true,
scope: {
attribute: '@',
collection: '='
},
link: (scope, element, attrs, model) ->
scope.selected = false
element.attr 'ng-click', 'toggle_selection()'
element.html "<i class='icon-check icon-white''></i>Select All"
scope.toggle_selection =() ->
scope.selected = !scope.selected
collection.forEach (item) ->
item[attribute] = scope.selected
scope.toggle_content()
scope.toggle_content =() ->
element.html("<i class='icon-check icon-white'></i>Select All") unless scope.selected
element.html("<i class='icon-check-empty icon-white'></i>Unselect All") if scope.selected
]
的Javascript:
App.directive("selectAll", [
function() {
return {
restrict: 'A',
replace: true,
scope: {
attribute: '@',
collection: '='
},
link: function(scope, element, attrs, model) {
scope.selected = false;
element.attr('ng-click', 'toggle_selection()');
element.html("<i class='icon-check icon-white''></i>Select All");
scope.toggle_selection = function() {
scope.selected = !scope.selected;
collection.forEach(function(item) {
return item[attribute] = scope.selected;
});
return scope.toggle_content();
};
return scope.toggle_content = function() {
if (!scope.selected) {
element.html("<i class='icon-check icon-white'></i>Select All");
}
if (scope.selected) {
return element.html("<i class='icon-check-empty icon-white'></i>Unselect All");
}
};
}
};
}
]);
的问题是,toggle_selection功能不会被调用。我尝试在我创建的元素上动态调用$compile
,但它引发了一个异常,表示编译没有定义。
此外,如果您有更好的方式来做我正在做的事情,请分享最佳做法,因为我使用Angular的时间不到一周。
谢谢!
看看'指令文件template'财产赞扬建议。你在做什么可以在指令模板中完成。指令模板可以包含绑定表达式,它可以根据状态($ scope)显示\隐藏和更改类。 – Chandermani