AngularJS - 使用动态类查找元素
-
20-12-2019 - |
题
我正在使用ng类添加类,但是当我尝试使用指令找到这些元素时,我无法找到它们。
.factory('loadTemplate', function($compile) {
return function(template) {
return {
restrict: 'E',
replace: true,
templateUrl: template,
link: function(scope, el, attrs) {
console.log(el.find('.step.disabled'));
}
}
}
})
.directive('step1', function(loadTemplate) {
return loadTemplate('processes/steps/step1.html');
})
.
但它没有找到元素(Chrome控制台输出):
context: div
length: 0
prevObject: o.fn.init[1]
selector: ".step.disabled"
__proto__: Object[0]
.
进程/步骤/ step1.html:
<div>
<div toggle-box>
<div class="step" ng-class="{enabled: condition, disabled: !condition}">
...
.
,我确定有。divs。
当我尝试仅使用$('step')找到元素时,我可以找到它们,因为该类已经存在。
如何解决这个问题?
这是一个斑块: http://plnkr.co/edit/afymqlx0wp3trffwraddd?p=preview
解决方案
我所需要的是等待Angular完成渲染视图,即使使用0次超时函数,它也会有效。像这样:
propunter示例: http://plnkr.co/edit/rcqyc4aipnlq1wtpahjp?p=preview
.factory('loadTemplate', function($timeout) {
return function(template) {
return {
restrict: 'E',
replace: true,
templateUrl: template,
link: function(scope, el, attrs) {
$timeout(function() {
$('.step.disabled').attr('border-color', '#f00');
}, 0);
}
}
}
})
.directive('step1', function(loadTemplate) {
return loadTemplate('processes/steps/step1.html');
})
. 不隶属于 StackOverflow