当我尝试在我自己的指令中设置setValidity()时,我遇到了不明确的情况。 它设置与表达式相反的值,表达式返回false,返回时返回true,返回true。 所以我的角色代码:
<script>
var userForm = angular.module("userForm", []);
userForm.directive('isEquals', function () {
return {
// element must have ng-model attribute.
require: 'ngModel',
scope: {
otherFieldValue: "=isEquals"
},
link: function (scope, elem, attr, ctrl) {
ctrl.$validators.isEquals = function (modelValue) {
console.log("otherFieldValue: " + scope.otherFieldValue);
console.log("modelValue: " + modelValue);
valid = (modelValue === scope.otherFieldValue);
ctrl.$setValidity('isEquals', valid);
console.log("valid: " + valid);
//Q1: is it in fact userForm.confirmPassword.$error.isEquals?
console.log("isEquals: " + ctrl.$error.isEquals);
console.log("modelValue: " + modelValue);
console.log("");
return modelValue;
};
scope.$watch("otherFieldValue", function () {
ctrl.$validate();
});
}
};
});
userForm.controller("userFormController", function ($scope, $http) {
});
</script>
和我的 html代码:
<div ng-app="userForm">
<form name="userForm" modelAttribute="userForm" ng-controller="userFormController" ng-submit="createUser()" novalidate>
<div class="row">
<input id="password" name="password" path="password" type="password" placeholder="Password" minlength="5" maxlength="60" ng-model="user.password" required/>
<br>
<span ng-show="userForm.password.$dirty && userForm.password.$error.required">Password field is required.<br></span>
<span ng-show="userForm.password.$dirty && userForm.password.$error.minlength || userForm.password.$error.maxlength">Password field must have size from 5 to 60 symbols.<br></span>
</div>
<div class="row">
<input id="confirmPassword" name="confirmPassword" path="confirmPassword" type="password" placeholder="Confirm Password" minlength="5" maxlength="60" ng-model="user.confirmPassword" equals-to="user.password" required/>
<br>
<span ng-show="userForm.confirmPassword.$dirty && userForm.confirmPassword.$error.required">Confirm Password field is required.<br></span>
<span ng-show="userForm.confirmPassword.$dirty && userForm.confirmPassword.$error.minlength || userForm.confirmPassword.$error.maxlength">Confirm Password field must have size from 5 to 60 symbols.<br></span>
<span id="m1" ng-show="userForm.confirmPassword.$dirty && !userForm.confirmPassword.$error.equalsTo">Passwords are not same.<br></span>
</div>
<div class="row">
<input id="submit" type="submit" ng-submit="createUser()" value="Sign Up"/>
</div>
</form>
</div>
但是当我输入密码时,我有下一种情况(我会签署&#34;密码不一样。&#34; AS m1):
//1) valid!=equalsTo, m1 visible. Have to be valid===equalsTo===false, m1 visible.
otherFieldValue: teste
modelValue: undefined
valid: false
equalsTo: true
modelValue: undefined
//2) valid!=equalsTo, equalsTo undefined. Have to be valid===equalsTo===true. m1 still visible, but has not to be.
otherFieldValue: teste
modelValue: teste
valid: true
equalsTo: undefined
modelValue: teste
我将感谢任何帮助,建议,链接和特别解释。提前谢谢。
编辑: 好的。无意中,我发现这是因为指令的名称和ctrl。$ validators.isEquals具有相同的名称。有什么问题,有人可以解释一下吗?