我对这个指令的意图是创建一个 Select-All 指令,它可以附加到任何类型的 html 元素以进行重用。
咖啡脚本:
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 不到一周。
谢谢!