關於angularjs中,數據模型被改變,頁面不刷新的解決辦法


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,就是為了異步負值用的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM