[英]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.