我在做输入掩码的指令。但是,当我将字符串作为值传递时,属性是未定义的。如果我直接通过面具,它就能用了。
.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是undefined (应该输入“money”):
<input type="teste" name="teste" value="" ng-model="form.email" input-mask='money'/>怎么啦?
发布于 2013-10-21 12:37:54
当您使用scope: true时,将为该指令创建一个新的作用域。然后,如果您的$watch工作正常,您应该为当前作用域(称为inputMask )创建一个接收attrs.inputMask的新属性。
scope.inputMask = attrs.inputMask;
scope.$watch('inputMask', function (newVal) {
console.log('inputMask', newVal);
});您可以看到一个简化的工作小提琴这里
另一个选项是在指令的作用域属性中使用散列对象。
指令文档写道:
{} (对象哈希)-创建了一个新的“隔离”范围。“隔离”作用域与正常作用域不同,因为它不典型地从父作用域继承。这在创建可重用组件时非常有用,这些组件不应该意外地读取或修改父作用域中的数据。 (...) @ or @attr -将本地范围属性绑定到DOM属性值。
这样,就可以创建绑定DOM属性的作用域:
scope: {
inputMask: "@"
},
link: function (scope, element, attrs) {
scope.$watch('inputMask', function (newVal) {
console.log('inputMask', newVal);
});
/* ... */
}小提琴
发布于 2013-10-21 18:59:24
在指令使用中,
范围:{inputMask:'@'}
在链接函数中,而不是使用attr.inputMask,使用scope.inputMask,这样就可以了。
如果您想使用attr,那么您可以使用
attr.$observe('inputMask', function() {
console.log('changed');
}因为最初的值将是未定义的。
发布于 2016-10-16 01:49:08
这里的实际问题是这个范围。$eval(‘money’)将返回未定义的值。如果它是大括号{},或者是一个字符串,比如'money‘,那么该属性应该很好地链接到指令。
造成问题的是你对价值所做的事情。
var maskType = scope.$eval(attrs.inputMask);如果您传递的是内插属性(如{{money}),则只需要在@中使用单独的作用域。
https://stackoverflow.com/questions/19494193
复制相似问题