我尝试编写自定义指令来验证输入值:它是否属于指定范围。问题是我无法在不知道用于ng-model
的范围变量的名称的情况下访问ng-model
。考虑到该指令必须重复使用不同的输入,我想直接访问ng-model
。我确实尝试使用scope[attrs.ngModel]
,但获得了undefined
值。如何在指令中读取ng-model
值?谢谢。
netupApp.directive('between', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
scope.$watch('dataSubmitting', function(dataSubmitting){
if (dataSubmitting) {
var min = Number(attrs.min);
var max = Number(attrs.max);
console.log(attrs.ngModel); // "number"
console.log(scope[attrs.ngModel]); // undefined
var inputText = scope.number; // that is the var used in ng-model
console.log(min); // 10
console.log(inputText); // would be the input value
console.log(max); //20
if (inputText <= min || inputText >= max) {
scope.alerts.push({
msg: 'error',
type: 'danger',
icon: 'warning',
'closable': true
});
}
}
});
}
};
});
答案 0 :(得分:1)
获取ngModel.$viewValue
的正确方法是:
app.directive('between', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$render = function () {
var newValue = ngModel.$viewValue;
console.log(newValue)
};
}
};
});
想要从ngModel.$setViewVAlue
directive
时,请查看下面的教程
https://egghead.io/lessons/angularjs-using-ngmodel-in-custom-directives
答案 1 :(得分:1)
您应该挂钩Angular验证系统并将验证器函数添加到$ validators或$ asyncValidators集合中(在您的情况下,我认为$ validators就足够了,不需要异步)。
验证器函数接收模型值作为参数:
link: function(scope, elm, attrs, ctrl) {
var min = Number(attrs.min);
var max = Number(attrs.max);
ctrl.$validators.between = function(modelValue, viewValue) {
if (modelValue <= min || modelValue >= max) {
//do something here or just return false
return false;
}
return true;
}
}
在视图中,您可以获得如下验证错误消息:
<div ng-messages="formName.inputName.$error">
<p ng-message="between">The value is not in the required range<p>
</div>
参考文档:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
答案 2 :(得分:0)
根据angluarJs doc:$parse 你需要解析attrs,请尝试:
var getter=$parse(attrs.ngModel);
var setter=getter.assign;
setter(scope,getter(scope));