【问题标题】:AngularJS: Behavior of $valid in Firefox vs. ChromeAngularJS:$valid 在 Firefox 与 Chrome 中的行为
【发布时间】:2014-12-01 16:19:04
【问题描述】:

我目前正在研究自定义验证指令。它在 Firefox 上运行流畅,但后来我决定在 Chrome 和 IE 上测试它,并想知道为什么它不能在其中任何一个上运行。

添加一些调试输出后,我注意到一个奇怪的行为。
在 Firefox 上选择和取消选择复选框时,我得到以下输出:

对象 { $viewValue=true, $modelValue=true, $parsers=[2], mehr...} 有效:真 对象 { $viewValue=false, $modelValue=false, $parsers=[2], mehr...} 有效:假

另一方面,在 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


【解决方案1】:

为了扩展我的评论,我怀疑输入初始化和模型更新存在浏览器差异。要抑制这种情况,请注意以下事项:

您将复选框绑定到$scope.tnc,但没有提供任何可以初始化的代码。 如果您有该视图的控制器,请尝试在开头设置 $scope.tnc = false;。

如果由于某种原因您在这里没有使用控制器,您也可以尝试在视图中添加初始化表达式,如下所示:

<input id="tnc" name="tnc" type="checkbox" data-ng-model="tnc" data-ng-init="tnc = false" [...]>

更新:好的,既然模型初始化差异现在已经没有问题了,也许这会帮助你解决视图状态不一致的问题:the ngChecked directive

将其附加到您的复选框输入并评估您的复选框值模型变量上的表达式。

【讨论】:

  • 我在问题中编辑了我的模型。它是用 false 初始化的 formData 的一部分。问题似乎是输入元素上的 $valid 表达式而不是模型。
猜你喜欢
  • 1970-01-01
  • 2015-09-24
  • 2010-11-29
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
  • 2017-08-09
  • 1970-01-01
  • 2019-03-07
相关资源
最近更新 更多