0

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

2 回答 2

0

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

您可以切换引号,以便字符串是有效的 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 并将对象引用从控制器传递到隔离范围

于 2016-02-05T15:18:30.843 回答
0

只需使用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'}" />
于 2016-02-05T15:31:36.563 回答