Unable to get the resolved attributes within custom directive

僤鯓⒐⒋嵵緔 提交于 2020-01-07 03:02:51

问题


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.

Thanks in advance


回答1:


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



回答2:


If you only want to evaluate the value once in the link function, you can use $interpolate (remember to inject it into your directive):

console.log($interpolate(element.attr('id'))(scope));

However, since you are likely using ng-repeat (because of the use of $index) I prefer @sza's answer, since your list may change, hence you may need to react to changes to your list.



来源:https://stackoverflow.com/questions/18496603/unable-to-get-the-resolved-attributes-within-custom-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!