问题描述
我一直在尝试为具有动态 id 的输入字段编写自定义指令,但在该指令中我无法获得正确的 id.
I have been trying to write a custom directive for an input field with dynamic id, in the directive am unable to get the correct id.
<input id="myInput{{$index}}" my-dir="fn()"/>
myApp.directive('myDir', function ($parse) {
var obj = {
require: "ngModel",
link: {
post: function (scope, element, attrs) {
var fn = $parse(attrs.myDir);
var elementId = element.attr('id');
console.log(elementId); // Here I see myInput{{$index}} instead of myInput0, by this time angular is not resolving the value
}
}
};
return obj;
});
我的问题是,如何在指令中获取解析值.此外,由于其他原因,我不能在这里使用任何孤立的作用域.
My question would be, how can I get the resolved value in the directive. Also I cannot use any isolated scope here due to other reasons.
提前致谢
推荐答案
您可以使用 $observe 观察包含插值的属性的值变化(例如 src="{{bar}}").这不仅非常有效,而且还是轻松获取实际值的唯一方法,因为在链接阶段尚未评估插值,因此此时该值设置为未定义.
You can use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.
post: function (scope, element, attrs) {
attrs.$observe('id', function (id) {
console.log(id)
})
}
这篇关于无法在自定义指令中获取解析的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!