我正在为输入掩码执行指令。但是,当我传递字符串作为值时,该属性未定义。如果我直接通过面具它就起作用了。
.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() + "'");
});
}
};
});
工作(将进入开关默认状态):
<input type="teste" name="teste" value="" ng-model="form.email" input-mask='{ "mask": "d/m/y", "autoUnmask" : true}'/>
不工作,attrs.inputMask是未定义
(应输入以防“钱”):
<input type="teste" name="teste" value="" ng-model="form.email" input-mask='money'/>
出了什么问题?
最佳答案
当您使用scope: true
时,将为该指令创建一个新范围。然后,为了让 $watch
正常工作,您应该为当前作用域创建一个名为 inputMask 的新属性,该属性接收 attrs.inputMask
scope.inputMask = attrs.inputMask;
scope.$watch('inputMask', function (newVal) {
console.log('inputMask', newVal);
});
您可以看到一个简化的工作 fiddle here
另一个选项是在指令的范围属性中使用哈希对象。
{} (object hash) - a new 'isolate' scope is created. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from the parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.
(...)
@ or @attr - bind a local scope property to the value of a DOM attribute.
这样,您就可以创建绑定(bind) DOM 属性的作用域:
scope: {
inputMask: "@"
},
link: function (scope, element, attrs) {
scope.$watch('inputMask', function (newVal) {
console.log('inputMask', newVal);
});
/* ... */
}
关于angularjs - 获取 Angular 指令属性值返回 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19494193/