【问题标题】:AngularJS - $watch not working as expectedAngularJS - $watch 没有按预期工作
【发布时间】:2016-02-15 06:06:53
【问题描述】:

这是我的 app.js

var MyApp = angular.module('MyApp', []);

MyApp.controller('MyController', ['$scope', function($scope){

  $scope.watchMe = 'hey';

  $scope.init = function() {
    setTimeout(function() {
      $scope.watchMe = 'changed!';
    }, 3000)

  };

  $scope.$watch('watchMe', function() {
     console.log($scope.watchMe)
  });

}]);

我想,3 秒后,我会看到:

'changed!'

在我的控制台中。

相反,我只是看到:

'hey'

我在 index.html 中调用我的 init() 函数,如下所示:

<div ng-controller="MyController"  ng-init="init()">

为什么我会看到这个输出?

【问题讨论】:

    标签: javascript angularjs output angularjs-digest


    【解决方案1】:
    var MyApp = angular.module('MyApp', []);
    
    MyApp.controller('MyController', ['$scope', '$timeout', function($scope, $timeout){
    
      $scope.watchMe = 'hey';
    
      $scope.init = function() {
      $timeout(function() {
          $scope.watchMe = 'changed!';
      }, 500);
    
      };
    
      $scope.$watch('watchMe', function(newVal, oldVal) {
         console.log(newVal);
      });
    
    }]);
    

    您正在使用 setTimeout 方法。 Angular 没有关注该事件。使用 Angular 的 $timeout 服务就可以看到预期的结果了。

    阅读有关角度摘要循环和脏检查的更多详细信息。

    【讨论】:

      猜你喜欢
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 2015-09-22
      • 1970-01-01
      相关资源
      最近更新 更多