我正在构建一个自定义指令来匹配两个输入字段。
因此,使用 ctrl.$parsers.unshift 会引发错误无法读取未定义的属性“unshift”
。无法弄清楚出了什么问题。
顺便说一句,我正在使用 Angular Material 输入字段。
<md-input-container>
<label>E-Mail</label>
<input required type="email" name="clientEmail" ng-model="user.clientEmail"
minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/" />
<div ng-messages="registerForm.clientEmail.$error" role="alert">
<div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
Your email must be between 10 and 100 characters long and look like an e-mail address.
</div>
</div>
</md-input-container>
<md-input-container>
<label>E-Mail wiederholen</label>
<input required type="email" name="clientEmailconfirm" ng-model="user.clientEmailconfirm"
minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/" field-match="{{user.clientEmail}}" />
<div ng-messages="registerForm.clientEmailconfirm.$error" role="alert">
<div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
Your email must be between 10 and 100 characters long and look like an e-mail address.
</div>
<div ng-message="fieldMatch">E-Mail do not Match...</div>
</div>
</md-input-container>
指令:
angular.module('fieldmatcher', []);
app.directive('fieldMatch', ['$rootScope', '$compile', '$parse', function($rootScope, $compile, $parse) {
return {
require: ['ngModel'],
restrict: 'A',
scope: true,
link: function(scope, element, attr, ctrl) {
ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);
var validate = function(viewValue) {
var comparisonModel = attr.fieldMatch;
if (!viewValue || !comparisonModel) {
ctrl.$setValidity('fieldMatch', true);
}
ctrl.$setValidity('fieldMatch', (viewValue === comparisonModel));
return viewValue;
};
attr.$observe('fieldMatch', function(comparisonModel) {
return validate(ctrl.$viewValue);
});
}
}
}]);
最佳答案
在您的示例中,链接函数的参数 ctrl
是一个具有单个 Controller 元素的数组。
这是因为您为 require
属性使用了数组值。
请参阅docs对于 ctrl
参数:
The exact value depends on the directive's require property:
1. no controller(s) required: the directive's own controller, or undefined if it doesn't have one
2. string: the controller instance
3. array: array of controller instances
因此只需更改为 require: 'ngModel',
。
并在将变量放入解析器和格式化程序数组之前定义var validate = function(...
。
关于angularjs - ctrl.$parsers.unshift 抛出未定义的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36112170/