0

在我的应用程序中,$watch如果表格在做一些事情之前是有效的。models问题是 ngForm在我使用它之前不会编译。

示例: http ://plnkr.co/edit/Y7dL67Fn7SaSEkjiFf2q? p=preview

JS

  $scope.results = [];
  $scope.$watch(function() {
    return $scope.testForm.$valid;
  },
    function( valid ) {
      $scope.results.push( valid );
    }
  )

HTML

<ng-form name="testForm" ng-init="test = 1">
  <input ng-model="test" required>
</ng-form>

<p ng-repeat="result in results track by $index" ng-class="{'false': !result, 'true': result}">{{ result }}</p>

结果 :

false // Wrong
true

表单最初不应无效,因为$scope.test设置为 1。

有什么线索吗?

4

2 回答 2

2

According to the docs:

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.


It (almost always) makes sense to ignore this first call using a check:

$scope.$watch('testForm.$valid', function (newValue, oldValue) {
    if (newValue === oldValue) { return; }
    $scope.results.push(newValue);
});

See, also, this short demo.

于 2014-05-21T22:01:03.433 回答
0

不确定是否正确理解,但可能是 AngularJS 第一次检查,

$scope.results = [];

是空的,因此在您将任何内容推入其中之前,结果评估为 false。

如果您从非空结果开始,请说:

$scope.results = [1];

第一次评价是真的。

我不认为 $watch 是正确的方法。我认为您的问题与 $watch 的工作方式以及 Angular 的摘要周期有关。

于 2014-05-21T21:39:47.077 回答