【发布时间】:2016-01-09 14:55:57
【问题描述】:
这是我用于指令的代码:
var compareTo = function() {
return {
require: "ngModel",
scope: {
otherModelValue: "=compareTo"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.compareTo = function(modelValue) {
console.log(modelValue + ":" + scope.otherModelValue);
return modelValue == scope.otherModelValue;
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
};
};
app.directive("compareTo", compareTo);
这是我的html:
<div class="form-group">
<label>Password</label>
<span>Must contain at least eight characters, including uppercase, lowercase letters and numbers</span>
<input type="password"
class="form-control"
name="password"
ng-model="signUpPass1"
ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/"
required>
<div ng-messages="signUpForm.password.$error" class="formMsgContainer">
<span class="formMsg" ng-message="pattern">Passwords Does Not Meet the Criterias!</span>
</div>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password"
class="form-control"
name="conPass"
ng-model="signUpPass2"
compare-to="signUpPass1"
required>
<div ng-messages="signUpForm.conPass.$error" class="formMsgContainer">
<span class="formMsg" ng-message="compareTo">Passwords Do Not Match!</span>
</div>
</div>
但是compareTo 指令不起作用。查看我在指令中输入的控制台日志,它打印出 pass2 的字符串和 pass1 的 undefined。如aaaa:undefined。这意味着它们永远不会相等,因此总会有错误。所以scope.otherModelValue这句话肯定有问题,但我似乎无法弄清楚哪里出了问题。
谢谢
【问题讨论】:
标签: angularjs forms angular-directive