动态元素未在AngularJS上调用指令方法
Dynamic element not calling directive method on a AngularJS
我使用该指令的目的是创建一个SelectAll指令,该指令可以附加到任何类型的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");
}
};
}
};
}
]);
问题是没有调用togg_selection函数。我试图对我动态创建的元素调用$compile
,但它引发了一个异常,表示未定义compile。
此外,如果你有更好的方法来做我正在做的事情,请分享最佳实践,因为我使用Angular的时间不到一周。
谢谢!
我没有发现原因,所以我改变了使用模板atribute的方法,正如@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
]
相关文章:
- 显示指令时调用指令方法
- AngularJS:如何调用指令中定义的函数'控制器的作用域
- 如何在ngRepeat中调用指令
- 未对输入更改调用指令
- 从子指令调用指令函数不起作用
- 从 AngularJS 中的父控制器调用指令的方法
- 从服务 AngularJS + TypeScript 调用指令
- 如何从 Angular 上的控制器调用指令的函数
- 如何从 JavaScript 调用指令函数
- Angular JS 如何从指令模板内容事件调用指令范围函数
- 从控制器调用指令中函数的最佳方法是什么
- 从传入的内容调用指令方法
- Angularjs-在ng-init函数完成后调用指令
- 从另一个指令调用指令
- 从父指令角度调用指令函数
- 如何从控制器调用指令作用域上的函数
- 有棱角的从html调用指令中的函数
- 动态元素未在AngularJS上调用指令方法
- 是'不良做法'用于Angular控制器调用指令上的函数
- AngularJS:从具有隔离作用域的控制器中调用指令中的函数