我对此指令的意图是创建一个Select-All指令,该指令可以附加到任何类型的html元素以供重用。
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不到一周。
谢谢!
答案 0 :(得分:0)
我没有发现原因,所以我改变了使用模板属性的方法,如@Chandermanji的建议
App.directive "selectall", [ ->
restrict: 'E',
replace : true,
scope: {
attribute: '@',
collection: '='
},
template: '<div class="btn btn-large btn-inverse" ng-click="toggle_selection(collection, attribute)">' +
'<i class="icon-check icon-white"></i>Select All' +
'</div>',
link: (scope, element, attrs, model) ->
scope.selected = false
scope.toggle_selection = (collection, attribute) ->
scope.selected = !scope.selected
scope.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
]