我有一个 AngularJS 应用程序,它在如下所示的 View 中列出来自服务器的数据:
<table class="table table-striped">
<tr ng-repeat="query in saved_queries">
<td ng-click="fill()"><a>{{ query.query_string }}</a></td>
<td class="pull-right" ng-click="kill_entry({{query.id}})"><i class="glyphicon glyphicon-remove"></i></td>
</tr>
</table>
saved_queries 对象由一个 id 为“refresh”的按钮填充,该按钮从该 Controller 运行一个名为 refreshSubmit() 的函数:
angular.module('myApp')
.controller('QueryCtrl', ['$scope', 'Query', function ($scope, Query) {
$scope.kill_entry = function(id){
var kill = $.post('http://my_ip:3000/api/delete_query', {'id': id});
kill.done(function(result){
$('#refresh').click();
});
}
$scope.refreshSubmit = function(){
var savedQueries = $.post('http://my_ip:3000/api/saved_queries');
savedQueries.done(function(result){
$scope.saved_queries = result;
})
}
$scope.saveSubmit = function() {
var save_query = $.post('http://my_ip:3000/api/save_query', { 'query_string': $scope.query_box });
save_query.done(function(result){
$('#refresh').click();
});
}
}
])
问题是,我必须点击“刷新”按钮两次,以便在创建或销毁记录后更新 View 中的数据。
理想情况下,只需单击一次。
知道为什么会这样吗?
最佳答案
您选择不完全遵循 AngularJS 哲学,这很好 - 这是您的选择。但是在选择使用 jQuery 的 $.post() 机制而不是 Angular 的 $http 机制时,您将跳过它通常会为您执行的步骤。添加一个
$scope.$apply();
调用您的 $.post()
结果回调,您的数据将立即更新。 AngularJS 需要这个作为触发器来知道模型数据何时可能已经改变并且它应该查看它(仅仅不断地轮询它跟踪的每个数据对象将是非常低效的)。或者,您可以使用 $http
执行相同的操作,而无需执行上述步骤。
关于javascript - Angular 中的数据未在预期时间更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25085550/