angularjs $apply 數據綁定 張映 發表於 2014-02-27 分類目錄: js/jquery 標簽:$apply, angular, angularjs, js js代碼都是順序執行的,如果遇到異步執行,並且帶有返回值,angularjs是怎么處理的呢?下面以實例詳細說明一下$apply的功能。 1,angularjs數據綁定了,但是沒有在html中顯示出來 查看復制打印? phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.user = ''; $scope.test = function() { setTimeout(function () { $scope.user = "good"; }, 2000); } $scope.test1 = function() { $scope.user = 'tank'; } $scope.test1(); $scope.test(); console.log($scope); } ]); 上例解釋: 正常理解是:在html顯示tank,2秒后,會變成good。 實際情況是:html顯示tank,2秒后,不會成good。 我開始以為是setTimeout里面的程序並沒有執行,但是我用console.log($scope);發現$scope.user值改變了,是good,但是為什么沒有在html里面體現出來呢。 怎么樣才能讓html中的{{user}}自動變呢。 查看復制打印? $scope.test = function() { setTimeout(function () { $scope.$apply(function () { $scope.user = "good"; }); }, 2000); } 這樣就可以了,在html顯示tank,2秒后,會變成good。 2,第三方登錄,登錄成功后,讀取返回值 查看復制打印? $scope.getUserInfo = function(response){ FB.api('/me', function(response1) { $scope.$apply(function() { $scope.user = { 'AccessToken':response.authResponse.accessToken, 'facebook_uid':response.authResponse.userID, 'name':response1.name } }); }); } 登錄到成功后,從第三方api接口,讀取個人信息,也是一個異步的過程。感覺$apply,就是為了異步負值用的。