无法获取自定义指令范围内解决的属性 [英] Unable to get the resolved attributes within custom directive

查看:156
本文介绍了无法获取自定义指令范围内解决的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图写动态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.

在此先感谢

推荐答案

您可以使用 $观察观察属性值的变化包含 插入(例如:SRC ={{栏}})。这不仅是非常有效的,但它也能轻松搞定在链接阶段插值尚未评估,因此该值时,设置为undefined 的实际价值,因为的唯一途径。

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)
    })
}

这篇关于无法获取自定义指令范围内解决的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆