繁体   English   中英

AngularJS-$ watch无法正常工作

[英]AngularJS - $watch not working as expected

这是我的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)
  });

}]);

我以为,三秒钟后,我会看到:

'changed!'

在我的控制台中。

相反,我只看到:

'hey'

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

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

为什么我看到此输出?

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服务,您可以看到预期的结果。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM