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