我有一个用户需要输入2次电子邮件的表单。 我在互联网上找到了(但不能再找到链接)一些角度代码做我想要的。 唯一的问题是当两封电子邮件相同时,一个输入仍然是类
.ng-invalid.ng脏
所以我无法提交表格。
我的代码如下:
的CSS:
.ng-invalid.ng-dirty{
border-color: #FA787E;
}
.ng-valid.ng-dirty{
border-color: #78FA89;
}
HTML:
<div ng-app="myApp">
<form name="formTemplate" novalidate>
<input id="email1" type="email" ng-model="currentForm.email1" name="email1" required>
<span ng-show="formTemplate.email1.$error.required && formTemplate.email1.$dirty">required</span>
<span ng-show="!formTemplate.email1.$error.required && formTemplate.email1.$error.email1 && formTemplate.email1.$dirty">invalid email</span>
<input id="email2" type="email" name="email2" ng-model="currentForm.email2" same-email required>
<span ng-show="formTemplate.email2.$error.required && formTemplate.email2.$dirty">Please confirm your email.</span>
<span ng-show="!formTemplate.email2.$error.required && formTemplate.email2.$error.noMatch && formTemplate.email1.$dirty">Emails do not match.</span>
</form>
</div>
的javascript:
var app = angular.module('myApp', ['UserValidation']);
angular.module('UserValidation', []).directive('sameEmail', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue, $scope) {
var noMatch = viewValue != scope.formTemplate.email1.$viewValue;
ctrl.$setValidity('noMatch', !noMatch)
})
}
}
})
这里有一个jsfiddle:http://jsfiddle.net/malamine_kebe/pq6fw04v/
答案 0 :(得分:0)
我更新您的jsfiddle。您不会从ctrl.$parsers.unshift
返回值。
ctrl.$parsers.unshift(function (viewValue, $scope) {
var noMatch = viewValue != scope.formTemplate.email1.$viewValue;
ctrl.$setValidity('noMatch', !noMatch);
return noMatch;
})
更新了jsfiddle