【问题标题】:Angularjs - Result is not updating when new create data has been addedAngularjs - 添加新的创建数据后结果不会更新
【发布时间】:2013-10-16 05:42:39
【问题描述】:

我知道这里有人问过这个问题,但我仍然被这个问题所困扰,在我将新数据添加到数据库后结果没有更新。

我有一个控制器用于添加和检索数据

.controller('GameCtrl', ['$scope', function(scope) {

  scope.createGame = function() {    
   Api.createGame(postData).then(function(result) {
     console.log(result);
     scope.$broadcast("event: list updated", true);
   }, function(result) {
    console.log(result.data.message);
    scope.showError = true;
    scope.data = 'Warning! '+result.data.message;
   });
  }; 



  var quizmaster = {};

  quizmaster.gameList = function() {
    Api.getGameList().then(function(result) {
      console.log(result.data);
      scope.games = [];
      scope.games = result.data;
    }, function(result) {
     console.log(result);
     });
  };

  scope.$on("event: list updated", function(value) {
    console.log('event update');
    quizmaster.gameList();
  });


}]);

广播事件工作正常,添加后调用 quizmaster.gameList() 函数加载游戏列表。控制台中显示的数据未更新,新创建的数据尚不存在。但是当我查看我的数据库时,新添加的数据已经存储了。它只需要刷新页面即可更新列表。在不刷新页面的情况下如何在视图中体现添加的数据?

感谢您的帮助!

更新:Api.getGameList() 是一项服务。

.factory('Api', function($http) {
  return {
    getGameList: function(params) {
      return $http({
        method  : 'GET',
        url     : api + 'games/list',
        params  : params,
        headers : {'X-GameApp-Token' : credential.token}
      });
    }
  }
});

【问题讨论】:

  • 如果 console.log(result.data) 没有显示新数据,那么您的 Web 服务没有返回新数据。我认为您应该发布一个问题,显示可能出现故障的服务器端代码。在 Chrome 中,您可以检查开发工具中的网络选项卡,以确认您没有得到所需的响应。

标签: angularjs angularjs-scope


【解决方案1】:

什么是 Api.getGameList()?如果它是在 Angular 之外完成的(即 then() 不是来自 $http 承诺),那么您必须通知 Angular 您的更改。在$scope.apply() 中设置数据:

$scope.$apply(function() {
    scope.games = result.data;
});

【讨论】:

  • 我更新了上面的代码,其中 Api.getGameList() 是一项服务,请检查。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-19
  • 1970-01-01
  • 2018-06-03
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多