无法将数组传递给角度指令

Cannot pass array to angular directive

本文关键字:指令 数组      更新时间:2023-09-26

无法将数组传递给 Angular 中的输入掩码插件。也许有人可以帮助我解决这个问题。

angular.module('myproject.directives').   
directive('inputMask', function() {
    return {
        restrict: 'A',
        scope: {
            inputMask: '@'
        },
        link: function(scope, el, attrs) {
            $(el).inputmask(attrs.inputMask);
        }
    };
});
<input type="text" input-mask="{'mask': '9{4} 9{4} 9{4} 9{4}[9]', 'autoUnmask': 'true'}" />

属性值将返回一个字符串,而不是传递给插件所需的对象

您可以切换引号,使字符串是有效的 JSON,然后将 json 解析为对象

<input type="text" input-mask='{"mask": "9{4} 9{4} 9{4} 9{4}[9]", "autoUnmask": "true"}' />

.JS

.directive('inputMask', function() {
    return {
        restrict: 'A',
        scope: {
            inputMask: '@'
        },
        link: function(scope, el, attrs) {
          var mask =JSON.parse(attrs.inputMask);
           $(el).inputmask(mask);
        }
    };
})

但实际上,这要简单得多,而不是将字符串放在 html 中并将对象引用从控制器传递到隔离范围

只需使用scope.$eval方法执行inputMask属性中的表达式:

angular.module('myproject.directives')  
.directive('inputMask', function() {
    return {
        restrict: 'A',
        scope: {
            inputMask: '@'
        },
        link: function(scope, el, attrs) {
            $(el).inputmask(scope.$eval(attrs.inputMask));
        }
    };
});
<input type="text" input-mask="{'mask': '9{4} 9{4} 9{4} 9{4}[9]', 'autoUnmask': 'true'}" />