问题描述
我正在做一个输入掩码指令.但是,当我将字符串作为值传递时,该属性未定义.如果我直接通过掩码它就可以工作.
I'm doing a directive for input mask. But, when I pass a string as value the attribute is undefined. If I pass directly the mask It's working.
.directive('inputMask', function () {
return {
restrict: 'EAC',
scope: true,
link: function (scope, element, attrs) {
scope.$watch('inputMask', function (newVal) {
console.log('inputMask', newVal);
});
var maskType = scope.$eval(attrs.inputMask);
switch (maskType) {
case 'phone':
$(element).inputmask("phone", {
url: '@Url.Content("~/Scripts/jquery-inputmask/phone-codes/phone-codes.json")',
onKeyValidation: function () { //show some metadata in the console
console.log($(this).inputmask("getmetadata")["name_en"]);
}
});
break;
case 'money':
$(element).inputmask("decimal", { digits: 2 });
break;
case 'moneyGrouped':
$(element).inputmask("decimal", {
radixPoint: ",",
autoGroup: true,
groupSeparator: ".",
groupSize: 3,
digits: 2
});
break;
case 'email':
$(element).inputmask('Regex', { regex: "[a-zA-Z0-9._%-]+@[a-zA-Z0-9-]+\\.[a-zA-Z]{2,4}" });
default:
$(element).inputmask(maskType);
}
$(element).inputmask(scope.$eval(attrs.inputMask));
$(element).on('keypress', function () {
scope.$eval(attrs.ngModel + "='" + element.val() + "'");
});
}
};
});
工作(将进入默认开关):
Working (will get into default of the switch):
<input type="teste" name="teste" value="" ng-model="form.email" input-mask='{ "mask": "d/m/y", "autoUnmask" : true}'/>
不工作,attrs.inputMask 是 undefined
(应该输入以防 'money'):
Not working, attrs.inputMask is undefined
(should enter in case 'money'):
<input type="teste" name="teste" value="" ng-model="form.email" input-mask='money'/>
怎么了?
推荐答案
当您使用 scope: true
时,将为此指令创建一个新的作用域.然后,为了您的 $watch
正常工作,您应该为当前范围创建一个名为 inputMask 的新属性,该属性接收 attrs.inputMask
When you use scope: true
a new scope will be created for this directive. Then, to your $watch
works correctly, you should create a new attribute to the current scope, called inputMask, that receives the attrs.inputMask
scope.inputMask = attrs.inputMask;
scope.$watch('inputMask', function (newVal) {
console.log('inputMask', newVal);
});
您可以在此处
另一种选择是在指令的范围属性中使用哈希对象.
The other option, is to use the a hash object in directive's scope attribute.
指令文档写道:
{}(对象哈希) - 创建一个新的隔离"范围.隔离"范围与正常范围的不同之处在于它不是原型从父作用域继承.这在创建可重用的时很有用组件,不应意外读取或修改其中的数据父作用域.
(...)
@ 或 @attr - 将局部范围属性绑定到 DOM 属性的值.
@ or @attr - bind a local scope property to the value of a DOM attribute.
这样,您就可以创建绑定 DOM 属性的范围:
That way, you can create your scope binding the DOM attribute:
scope: {
inputMask: "@"
},
link: function (scope, element, attrs) {
scope.$watch('inputMask', function (newVal) {
console.log('inputMask', newVal);
});
/* ... */
}
这篇关于获取角度指令属性值返回“未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!