我有基本的表单输入指令,可以根据名称设置一些表单元素:
angular.module('myApp').directive('formInput', function () {
return {
restrict: 'A',
require: '^form',
link: function (scope, element, attributes, form) {
var input, name;
input = element[0].querySelector('input, textarea, select');
name = input.getAttribute('name');
// ...
// do stuff with input, name, form etc.
}
};
});
在我的 HTML 中,我做了一些简单的 DOM 设置,它起到了作用。
<div form-input>
<input type="text" name="myElement"/>
</div>
当我开始使用动态名称时,问题就来了,即
<div form-input>
<input type="text" name="{{ getDynamicName(element) }}"/>
</div>
在进入我的指令之前不会评估动态名称。有办法解决这个问题吗?
附言鉴于指令的装饰性,我不喜欢使用隔离范围。
最佳答案
在链接内部元素后使用0ms的$timeout
服务运行代码:
// Note that $timeout is now injected to the directive
angular.module('myApp', []).directive('formInput', function ($timeout) {
return {
restrict: 'A',
//require: '^form',
link: function (scope, element, attributes, form) {
$timeout(function() {
var input, name;
input = element[0].querySelector('input, textarea, select');
name = input.getAttribute('name');
alert(name);
}, 0);
// ...
// do stuff with input, name, form etc.
}
};
});
关于javascript - AngularJS - 检索评估的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33887956/