我目前正在處理自定義驗證指令。它在Firefox上運行平穩,但後來我決定在Chrome和IE上測試它,並想知道爲什麼它不能在其中任何一個上運行。AngularJS:在Firefox和Chrome中有效的行爲
添加一些調試輸出後,我注意到一個奇怪的行爲。
當選擇和不選擇在Firefox的複選框我獲得以下的輸出:
Object { $viewValue=true, $modelValue=true, $parsers=[2], mehr...} valid: true Object { $viewValue=false, $modelValue=false, $parsers=[2], mehr...} valid: false
在Chrome,另一方面我獲得以下的輸出:
Constructor {$viewValue: undefined, $modelValue: false, $parsers: Array[2], $formatters: Array[2], $viewChangeListeners: Array[0]…} valid: false Constructor {$viewValue: true, $modelValue: true, $parsers: Array[2], $formatters: Array[2], $viewChangeListeners: Array[0]…} valid: true
的$ 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'?如果不是,它可能確實是未定義的。 – kasoban 2014-10-07 09:24:16