angularjs $apply 數據綁定


js代碼都是順序執行的,若是遇到異步執行,而且帶有返回值,angularjs是怎麼處理的呢?下面以實例詳細說明一下$apply的功能。html

1,angularjs數據綁定了,可是沒有在html中顯示出來angularjs

app.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);  
  }  
]);

上例解釋:app

正常理解是:在html顯示tank,2秒後,會變成good。異步

實際狀況是:html顯示tank,2秒後,不會成good。code

我開始覺得是setTimeout裏面的程序並無執行,可是我用console.log($scope);發現$scope.user值改變了,是good,可是爲何沒有在html裏面體現出來呢。htm

怎麼樣才能讓html中的{{user}}自動變呢。io

$scope.test = function() {  
    setTimeout(function () {  
        $scope.$apply(function () {  
            $scope.user = "good";  
        });  
    }, 2000);  
}

這樣就能夠了,在html顯示tank,2秒後,會變成good。console

相關文章
相關標籤/搜索