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

时间:2014-08-01 17:26:23

标签: javascript angularjs

我有一个AngularJS应用程序,它在视图中列出来自服务器的数据,如下所示:

<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为&#34;刷新&#34;的按钮填充的。从该控制器运行一个名为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();
     });
   }
  }
])

问题是,我必须点击&#34;刷新&#34;按钮TWICE,以便在创建或销毁记录后更新视图中的数据。

理想情况下,只需点击一次即可。

知道为什么会这样吗?

2 个答案:

答案 0 :(得分:2)

你选择不完全遵循AngularJS理念,这很好 - 这是你的选择。但是在选择使用jQuery的$ .post()机制而不是Angular的$ http机制时,你正在跳过它通常会为你做的一个步骤。添加

$scope.$apply();

调用$.post()结果回调,您的数据会立即更新。 AngularJS要求这个作为触发器来知道模型数据何时可能已经改变并且它应该查看它(仅仅不断地轮询它跟踪的每个数据对象将是非常低效的)。或者,您可以使用$http执行相同的操作,而不需要执行上述步骤。

答案 1 :(得分:0)

使用$ http服务,该服务将触发$摘要周期并更新您的视图。 我会直接调用refreshSubmit方法而不是使用jquery来触发click事件。

angular.module('myApp')
  .controller('QueryCtrl', ['$scope', 'Query', '$http', function ($scope, Query, $http) {
     $scope.kill_entry = function(id){
        var kill = $http.post('http://my_ip:3000/api/delete_query', {'id': id});
        kill.success(function(result){
            $scope.refreshSubmit();
        });
     }
     $scope.refreshSubmit = function(){
       var savedQueries = $http.post('http://my_ip:3000/api/saved_queries');
       savedQueries.success(function(result){
          $scope.saved_queries = result;
        })
      }
      $scope.saveSubmit = function() {
        var save_query = $http.post('http://my_ip:3000/api/save_query', { 'query_string': $scope.query_box });
        save_query.success(function(result){
            $scope.refreshSubmit();
     });
   }
  }
])

将$ http请求移动到工厂也会更好。这样可以更轻松地测试控制器并更好地分离关注点。