【发布时间】:2014-12-01 16:19:04
【问题描述】:
我目前正在研究自定义验证指令。它在 Firefox 上运行流畅,但后来我决定在 Chrome 和 IE 上测试它,并想知道为什么它不能在其中任何一个上运行。
添加一些调试输出后,我注意到一个奇怪的行为。
在 Firefox 上选择和取消选择复选框时,我得到以下输出:
另一方面,在 Chrome 上,我得到以下输出:
构造函数 {$viewValue: undefined, $modelValue: false, $parsers: Array[2], $formatters: Array[2], $viewChangeListeners: Array[0]…} 有效:假 构造函数 {$viewValue: true, $modelValue: true, $parsers: Array[2], $formatters: Array[2], $viewChangeListeners: Array[0]…} 有效:真$viewValue 在第一次调用时未定义。然后它的行为就好像由于某种原因倒置一样。
有谁知道这种行为的原因和可能的解决方案?
JavaScript:
angular.module("gewinnspielApp").directive("customValidity", function() {
return {
restrict: "A",
scope: {
customText: "@customValidity",
},
require: "?ngModel",
link: function(scope, element, attrs, ngModel) {
element[0].setCustomValidity(scope.customText);
element.bind("change", function() {
console.log(ngModel);
console.log("valid: " + ngModel.$valid);
element[0].setCustomValidity((ngModel.$valid ? "" : scope.customText));
});
}
}
});
HTML:
<td style="border:none; padding-right: 4px; width: 10px;">
<input id="tnc" name="tnc" type="checkbox" data-ng-model="formData.tnc" required data-ng-class="{'ng-dirty': submitted, 'ng-pristine': !submitted}" data-custom-validity="Bitte akzeptieren Sie die Nutzungsbedingungen.">
</td>
编辑:
看起来模型更新和更改侦听器有问题。当我在 HTML 页面中添加 {{ myForm.tnc.$valid }} 时,该值与预期结果匹配。
【问题讨论】:
-
你在某处初始化
$scope.tnc吗?如果不是,它可能确实是未定义的。
标签: angularjs validation angularjs-directive cross-browser