Getting angular directive attribute value returns 'undefined'

纵然是瞬间 提交于 2019-12-06 12:04:06

When you use scope: true a new scope will be created for this directive. Then, to your $watch works correctly, you should create a new attribute to the current scope, called inputMask, that receives the attrs.inputMask

scope.inputMask = attrs.inputMask;
scope.$watch('inputMask', function (newVal) {
    console.log('inputMask', newVal);
});

You can see a simplified Working fiddle here

The other option, is to use the a hash object in directive's scope attribute.

The directive docs writes:

{} (object hash) - a new 'isolate' scope is created. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from the parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.

(...)

@ or @attr - bind a local scope property to the value of a DOM attribute.

That way, you can create your scope binding the DOM attribute:

scope: { 
    inputMask: "@" 
},
link: function (scope, element, attrs) {
    scope.$watch('inputMask', function (newVal) {
        console.log('inputMask', newVal);
    });
    /* ... */
}

Fiddle

In the directive use,

scope: {inputMask: '@'}

And in the link function instead of using attr.inputMask use scope.inputMask and that will work.

If you want to use attr then you can use

attr.$observe('inputMask', function() {
    console.log('changed');
}

Because initially the value will be undefined.

The actual problem here was that scope.$eval('money') will return undefined. The attribute should be linking just fine to the directive, if it's in curly braces {}, or if it's a string such as 'money'.

It's what you're doing with the value that's causing the problem.

var maskType = scope.$eval(attrs.inputMask);

You would only need to use isolated scope with @, or attrs.$observe if you were passing interpolated attributes, such as {{money}}.

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