理解Angular中的$apply()以及$digest()
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body ng-app="myApp"> <div ng-controller="MessageController"> Delayed Message: {{message}} </div> 你应该使用$timeout service来代替setTimeout(),因为前者会帮你调用$apply(),让你不需要手动地调用它 <script src="angular.min.js"></script> <script> angular.module(‘myApp‘,[]).controller(‘MessageController‘, function($scope) { $scope.getMessage = function() { /* setTimeout(function() { $scope.message = ‘Fetched after 3 seconds‘; console.log(‘message:‘+$scope.message); }, 2000); */ setTimeout(function() { $scope.$apply(function() { //wrapped this within $apply $scope.message = ‘Fetched after 3 seconds‘; console.log(‘message:‘ + $scope.message); }); }, 2000); } $scope.getMessage(); }); </script> </body> </html>
时间: 2024-11-07 05:46:09