簡體   English   中英

無法將數組傳遞給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'}" />

該屬性值將返回字符串,而不是傳遞給插件所需的對象

您可以切換引號,以便該字符串是有效的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屬性中執行表達式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'}" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM