随身笔记
随身笔记

$apply()解释说明

$apply()是用来告诉并提醒angular,在model上已经有更新了也请及时更新view。
那么我们什么时候使用$apply()?
例如:

angular.module('myApp',[]).controller('MessageController', function($scope) { 
 
  $scope.getMessage = function() { 
     setTimeout(function() { 
      $scope.message = 'Fetched after 3 seconds'; 
      console.log('message:'+$scope.message); 
     }, 2000); 
  } 
  $scope.getMessage(); 

});

我们使用的是setTimeout方法更新$scope.message的值,同时也希望更新的值在view也及时刷新,但是用这种方法view是不能及时更新的。因为angular并不知道$scope.message有更新。

这时候我们就使用$apply()了,将更改的数值写在$apply()里面,这样就能让angular知道$scope.message有变化也请及时更新view。例如:

angular.module('myApp',[]).controller('MessageController', function($scope) { 
 
   $scope.getMessage = function() { 
      setTimeout(function() { 
        $scope.$apply(function() { 
          $scope.message = 'Fetched after 3 seconds'; 
          console.log('message:' + $scope.message); 
         }); 
      }, 2000); 
   } 
 
  $scope.getMessage(); 
 
 });

如果是需要setTimeout()功能的话,其实推荐使用$timeout,因为它可以自动调用$apply()来提醒angular告诉有model变化了。

总结:需要记住的最重要的是AngularJS是否能检测到你对于model的修改。如果它不能检测到,那么你就需要手动地调用$apply()。

随身笔记

$apply()解释说明
$apply()是用来告诉并提醒angular,在model上已经有更新了也请及时更新view。 那么我们什么时候使用$apply()? 例如: angular.module('myApp',[]).controller('MessageController', f…
扫描二维码继续阅读
2015-02-06