从指令向元素动态添加角度属性 [英] Dynamically add angular attributes to an element from a directive
问题描述
我正在尝试构建一个指令来更改按钮上的加载状态以进行慢速 ajax 调用.基本上这个想法是为按钮元素设置一个属性ng-loading",然后让指令添加其余的东西.
I'm trying to build a directive that change loading status on buttons for slow ajax calls. Basically the idea is to set an attribute "ng-loading" to a button element, and let the directive add the rest of stuff.
这是html代码:
<button class="btn btn-primary" name="commit" type="submit" ng-loading="signupLoading">
Submit
</button>
这是指令代码:
.directive('ngLoading', ['$compile', function($compile) {
return {
restrict: 'A',
replace: false,
terminal: true,
link: function(scope, element, attrs) {
element.attr('ng-class', '{loading:' + attrs['ngLoading'] +'}');
element.attr('ng-disabled', attrs['ngLoading']);
element.append(angular.element('<img class="loading-icon" src="/assets/images/loading-icon.gif"/>'));
$compile(element.contents())(scope);
}
};
}]);
在呈现的 HTML 中看起来一切都是正确的,但是从指令添加的属性根本不起作用.我可以将这些属性移动到 HTML 代码中,一切都很好,但在许多地方这是相当多的冗余代码.
It all looks correct in the rendered HTML, but the attributes added from the directive is not funcioning at all. I can move those attributes to the HTML code and everything works great, but that's quite some redundant code in many places.
我参考了帖子 Angular 指令来动态设置现有 DOM 元素上的属性,但它不能解决我的问题.
I referenced the post Angular directive to dynamically set attribute(s) on existing DOM elements but it does not solve my problem.
欢迎任何评论/建议.提前致谢.
Any comment/suggestion are welcome. Thanks in advance.
推荐答案
如果你想要的只是一些 DOM 操作,你不需要重新编译该指令,你可以添加和删除关于范围属性更改的类.您可以改用 $watch.
You don't need to recompile that directive if all you want is some DOM manipulation, you can add and remove class in regards to the changes of a scope property. You can use $watch instead.
JAVASCRIPT
.directive('ngLoading', function() {
return function(scope, element, attrs) {
var img = angular.element('<img class="loading-icon" src="/assets/images/loading-icon.gif"/>');
element.append(img);
scope.$watch(attrs.ngLoading, function(isLoading) {
if(isLoading) {
img.removeClass('ng-hide');
element.addClass('loading');
element.attr('disabled', '');
} else {
img.addClass('ng-hide');
element.removeClass('loading');
element.removeAttr('disabled');
}
});
};
});
注意:您的代码不起作用,因为它编译元素的内容,而不是元素本身,您在其中附加了已实现的属性.
Note: Your code doesn't work because it compiles the contents of the elements, not the element itself, where you attach the attributes you have implemented.
尝试 $compile(elem)(scope);
它应该可以正常工作,但我不推荐它,因为每个具有此类指令的元素都必须再次重新编译.
try $compile(elem)(scope);
and it should work properly, but I don't recommend it because each element with such directive will have to re-compile again.
更新:在使用 $compile
之前删除元素的 'ngLoading' 属性以防止无限编译.
UPDATE:
before using $compile
remove the attribute 'ngLoading' to the element to prevent infinite compilation.
elem.removeAttr('ng-loading');
$compile(elem)(scope);
这篇关于从指令向元素动态添加角度属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!