javascript - Angular 中的数据未在预期时间更新

标签 javascript angularjs

我有一个 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/

相关文章:

javascript - 使用 jquery 重置表单会导致意外的语法错误

javascript - Material UI Card box-shadow 被 chop

javascript - Angularjs - 属性等于值

javascript - 带有正则表达式的 jQuery 选择器

javascript - 等待页面加载或等待 X 秒后再加载播放器

javascript - 脚本不循环显示图像

javascript - 单独的导航栏 Ctrl 用于单页应用程序

angularjs - 为什么 angularjs 的常量不能与工厂一起使用

angularjs - AngularJs 中 ng-model 的 Getter & setter 支持

javascript - Angular 和 JSON 交互?