无法将数组传递给 angular 指令

Cannot pass array to angular directive

无法将数组传递给 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'}" />

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

您可以切换引号以使字符串有效 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'}" />