gpt4 book ai didi

angularjs - 获取 Angular 指令属性值返回 'undefined'

转载 作者:行者123 更新时间:2023-12-04 04:37:31 25 4
gpt4 key购买 nike

我正在为输入掩码做一个指令。但是,当我将字符串作为值传递时,属性是未定义的。如果我直接通过面具它正在工作。

.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 (应输入以防“钱”):
<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

另一种选择是在指令的范围属性中使用哈希对象。

directive docs写道:

{} (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);
});
/* ... */
}

Fiddle

关于angularjs - 获取 Angular 指令属性值返回 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19494193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com