Angular JS - 即时更新视图
问题描述:
当用户点击像锚标签时,我想立即更新{{card.likeCount}}(在HTML页面上)。Angular JS - 即时更新视图
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<li>
<i class="fa fa-eye">
</i>
{{card.likeCount}}
</li>
<li>
<a href="#" ng-click="likingCard(card.id)" name>
Like
</i>
</a>
</li>
这是我现在该怎么办呢,我这个代码添加到cardCtrl,我不知道如果我用正确的方法:
$scope.likingCard = function(id) {
$http.post('/card/like/', {
id: id
}).then(function onSuccess(result, status, headers, config) {
setTimeout(function() {
$scope.likeCount = parseInt(result.data.likeCount);
console.log($scope.likeCount);
$scope.$digest();
}, 1000);
}).catch(function onError(err) {
console.log('Error:', err);
})
}
答
化妆使用ng-cloak指令
<body ng-cloak>
<!-- all your angular stuff here -->
</body>
你也可以使用ng-cloak直接在<html>
标签
以了解详情文档这里
答
我不明白为什么,当你说“即时更新”,你已经接收到响应之后插入故意延迟1秒在更新模型之前。
如果你不想延迟,只是更新模型:
$scope.likingCard = function(id) {
$http.post('/card/like/', {
id: id
}).then(function (result) {
$scope.likeCount = parseInt(result.data.likeCount);
console.log($scope.likeCount);
}).catch(function (err) {
console.log('Error:', err);
})
}
如果你想延迟那么就不要使用setTimeout
,使用$timeout
来代替,而你将不再需要显式调用到$digest
。
$scope.likingCard = function(id) {
$http.post('/card/like/', {
id: id
}).then(function (result) {
$timeout(function() {
$scope.likeCount = parseInt(result.data.likeCount);
console.log($scope.likeCount);
}, 1000);
}).catch(function (err) {
console.log('Error:', err);
})
}