我正在学习“使用Angular,Node和Token身份验证创建应用程序”教程。而且我已经卡住了。我在那里找到了这个代码:
HTML
<form name="register" class="form-signin" novalidate>
<h1 class="form-signin-heading text-muted">Register</h1>
<input type="email" ng-model="email" name="email" class="form-control" placeholder="Email address" required autofocus>
<p class="help-block" ng-show="register.email.$dirty && register.email.$invalid">Please enter a proper email.</p>
<input type="password" name="password" ng-model="password" class="form-control" placeholder="Password" required>
<input type="password" name="password_confirm" ng-model="password_confirm" class="form-control" placeholder="Confirm Password" validate-equals="password">
<p class="help-block" ng-show="register.password_confirm.$invalid && register.password_confirm.$dirty">please match the passwords.</p>
<button ng-disabled="register.$invalid" class="btn btn-lg btn-primary btn-block" type="submit">
Submit
</button>
</form>
和js
angular.module('myApp', []).directive('validateEquals', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
function validateEqual(value) {
var valid = (value === scope.$eval(attrs.validateEquals));
ngModelCtrl.$setValidity('equal', valid);
return valid ? value : undefined;
}
ngModelCtrl.$parsers.push(validateEqual);
ngModelCtrl.$formatters.push(validateEqual);
scope.$watch(attrs.validateEquals, function() {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
}
};
});
根据视频的这个指令应该给我一个适当的双向验证password
和password_confirm
输入,但它没有(在视频上它确实有效,我很困惑)。当我更改password_confirm
的值但是当我更改password
时,验证无效。这是plunker plunker。问题:该代码有什么问题?我该如何解决?
答案 0 :(得分:1)
问题可能就在这一行:
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
此行没有任何作用。我在之前版本的Angular中得到了sthat,它重新触发了$ parsers管道,并且在当前版本中,因为它将视图值设置为已经具有的相同值,所以它已被优化为不执行任何操作。
这对我来说真的像个黑客。它应该被替换为
之类的东西scope.$watch(attrs.validateEquals, function(firstPassword) {
var valid = (ngModelCtrl.$modelValue === firstPassword);
ngModelCtrl.$setValidity('equal', valid);
});
(未经测试)
BTW,angular现在支持验证器,这使得事情变得更容易,并且不会强迫您处理解析器和格式化程序:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController。答案 1 :(得分:0)
找到解决方案,感谢JB Nizet:)
解决方案:
angular.module('learningAngularApp')
.directive('validateEquals',
function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$validators.validateEqual = function(modelValue, viewValue) {
var value = modelValue || viewValue;
var valid = (value === scope.$eval(attrs.validateEquals));
return valid;
}
scope.$watch(attrs.validateEquals, function () {
ngModelCtrl.$validate();
});
}
};
});