Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 视图未按预期更新_Javascript_Html_Angularjs - Fatal编程技术网

Javascript 视图未按预期更新

Javascript 视图未按预期更新,javascript,html,angularjs,Javascript,Html,Angularjs,我的控制器中有以下设置,我希望适当地更新我的视图,但在刷新页面之前不会: var vm = this; var loadingGames = $q.defer(); var getGames = function() { playersService.getGames({ playerId: playerId }).$promise.then(function(data) { vm.games = data; loadingGames.resolve();

我的控制器中有以下设置,我希望适当地更新我的视图,但在刷新页面之前不会:

var vm = this;
var loadingGames = $q.defer();

var getGames = function() {
  playersService.getGames({
    playerId: playerId
  }).$promise.then(function(data) {
    vm.games = data;
    loadingGames.resolve();
  });
};

var init = function() {
  getGames();
}

init();

var updateSchedule = function() {
  getGames();
  loadingGames.promise.then(function() {
    populateOptions(vm.games);
    vm.tableParams.reload();
  });
};

vm.performAction = function(action, gameId, gameType) {
  utilitiesService.performOperation(action, gameId, gameType).then(
    function() {
      updateSchedule();
    },
    function(httpError) {
      alert('Couldn\'t '+ action +' game: ' + httpError);
    });
};

var populateOptions = function(games) {
  angular.forEach(games, function(game) {
    game.options = getOptions(game);
  });
};

当我在UI中单击
performation
按钮时,我希望在我的视图中看到更新的
vm.games
。但是,我总是需要刷新页面才能看到更改。我知道这很可能与
$scope.$apply
有关,但我目前还没有掌握它。

错误是您的loadingGames变量。您只实例化一次,并尝试多次解析它。当您首先从init函数调用它时,您将解析它。因此,所有在loadingGames上中继的对getGames的后续调用都不会等待,因为承诺已经解决。因此,他们正在使用旧的vm.games


要解决此问题,只需返回playerService的承诺。您可以链接promise,这意味着,通过允许实际的then并从您的服务返回promise,vm.games=数据将在下一个then中的代码之前执行。因此,您将从其他函数调用getGames.then(…)

您确定
populateOptions
vm.tableParams.reload()
是同步的吗?如何在视图中绑定游戏?当您将vm设置为该值时,这是指控制器吗?@Franck,是
这是指控制器。我使用
controllerAs
语法。
getOptions
是否返回承诺?这是一个角度承诺吗?所以你的视图绑定到游戏而不是vm.games,对吗?不幸的是,我在使用此结构时遇到了一个
无法读取未定义的
属性'then'的错误:
var updateSchedule=function(){getGames().then(function(){populateOptions(vm.games);vm.tableParams.reload();})您需要从getGames返回承诺。所以返回PlayerService.getGames({playerId:playerId})。$promise