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

相关文章
相关标签/搜索