代码如下,为什么页面的文本在2秒之后没有变成 world
<body ng-app="myApp">
<p ng-controller="asyncCtrl">
<input type="text" ng-model="name">
<span>{{name}}</span>
</p>
<script src="../../bower_components/angular/angular.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp',[]);
myApp.controller('asyncCtrl',function($scope,$http){
$scope.name = "hello";
setTimeout(function(){
$scope.name = "world";
},200);
})
</script>
</body>
另,通过$http
拿到的后台数据,如何赋值给model
,然后自动更新视图?
PS:好吧,其实两个问题都是一个问题。。
PHP中文网2017-04-10 17:41:45
setTimeout脱离了ng的监管,属于临时工性质,故ng底层不会自动执行脏检测更新视图,需要手动$scope.$apply()强制执行脏检测刷新视图,或者用楼上说的方法,使用ng封装过的“官方认可根正苗红”的$timeout来延迟执行。
PHP中文网2017-04-10 17:41:45
不要用 setTimeout
用 $timeout
var myApp = angular.module('myApp',[]);
myApp.controller('asyncCtrl',
function($scope,$http,$timeout){
$scope.name = "hello";
$timeout(function(){
$scope.name = "world";
},200);
});
举例来说,如果用 $http
做 GET 请求获取数据,获取数据后再用 success 回调方法来赋值,代码如下:
$http.get({ url: '/api/foo' })
.success(function(response) {
$scope.name = response
});
希望有所帮助~ :)