我写了一个match-model
当用户在我的应用程序中注册时,我用于密码/密码重复过程的角度指令。密码重复字段具有此特定属性,可根据原始密码字段验证此字段。
我的指令有scope.$watch
出于优化目的,因为我不必每次验证重复密码范围属性时都读取相关范围属性值,但我宁愿只使用缓存值,该值会在相关范围属性值更改(原始密码)时更改。
这是我的指令:
.directive("matchModel", ["$timeout", function ($timeout) {
return {
require: "ngModel",
link: function (scope, element, attributes, ngModelController) {
var valueCache = null;
// watch "match-model" model property value
scope.$watch(attributes["matchModel"], function (newValue, oldValue) {
valueCache = newValue;
/*
scope.$apply(); // error $digest in progress
$timeout(function () { scope.$digest(); }); // no error, not working
$timeout(function () { scope.$apply(); }); // no error, not working
*/
});
// add model validation parser
ngModelController.$parsers.unshift(function (value) {
ngModelController.$setValidity("match", value === valueCache);
return value === valueCache ? value : undefined;
});
}
};
}]);
我的表单包含两个字段(与此问题相关):
<input type="password" name="password" id="password" placeholder="password"
class="validate" autocomplete="off"
required
ng-minlength="6"
ng-model="data.password" />
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="repeat password"
class="validate" autocomplete="off"
required
ng-model="data.passwordRepeat"
match-model="data.password" />
要求
- 当用户输入第一个密码时,输入足够的字符后字段将变得有效 - 在上述情况下为 6 个字符
- 当用户输入第二个密码时,当数据与第一个密码匹配时,字段应变为有效
- 如果用户返回第一个字段并更改原始密码,则第二个字段应无效
目前如何运作
1 和 2 按预期工作,但 3 没有。这就是为什么我想添加scope.$digest
将范围模型更改传播到其他字段。和scope.$watch
是正确的时机,因为它在特定范围模型属性更改时执行。
看起来scope.$digest
(or scope.$apply
就此而言)不验证模型。验证似乎没有随之执行。
Question
那么我应该怎么做scope.$validate
甚至更好element.$validate
所以它只会验证我的特定字段而不是整个模型(导致用户界面中的形式无效)。