Javascript 数据未在预期时间以角度更新

Javascript 数据未在预期时间以角度更新,javascript,angularjs,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-clic

我有一个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>
问题是,我必须单击“刷新”按钮两次,以便在创建或销毁记录后更新视图中的数据

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


知道为什么会这样吗

您选择了不完全遵循AngularJS哲学,这很好——这是您的选择。但是在选择使用jQuery的$.post()机制而不是Angular的$http机制时,您跳过了它通常为您所做的一步。添加

$scope.$apply();

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

使用$http服务,它将触发$digest循环并更新您的视图。 我将直接调用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请求移动到工厂。这使得测试控制器变得更容易,并且可以更好地分离关注点。

在Angular中不要将JQuery用于ajax调用。使用
$http
服务,Angular将在请求完成时更新视图。
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();
     });
   }
  }
])