我正在使用Angular 1.5.9
和angular-route 1.5.9
。我有一个可行的解决方案,但对我而言,我需要$scope.$apply()
才能更新DOM。
我正在使用工厂和控制器来更新在ng-repeat
中使用的数组。我知道摘要循环没有被触发,这就是为什么我需要使用$scope.apply()
,但我不明白为什么。这是错误的代码:
myApp.controller('MyGamesController', ['$http', '$firebaseAuth', 'DataFactory', '$scope', function ($http, $firebaseAuth, DataFactory, $scope) {
console.log('mygamescontroller running');
var self = this;
self.newGame = {}
self.games = [];
getGames();
function getGames() {
DataFactory.getGames().then(function (response) {
console.log('returned to controller from factory', response); // logs the correct response including lastest data, but DOM doesn't update
self.games = response; // self.games is correctly set, but not updated on the DOM
$scope.$apply(); // Updates the DOM
});
} //end getgames function
self.addGame = function() {
DataFactory.addGame(self.newGame).then(getGames);
}
}]); //end controller
角路由器正在处理我的controllerAs
像这样:
.when('/mygames' ,{
templateUrl: '/views/templates/mygames.html',
controller: 'MyGamesController',
controllerAs: 'mygames'
})
以及用于在HTML的NG-重复部分的HTML看起来像这样:
<tbody>
<tr ng-repeat="game in mygames.games">
<td>{{game.game}}</td>
<td>{{game.number_players}}</td>
<td>{{game.time_to_play}}</td>
<td>{{game.expansion}}</td>
</tr>
</tbody>
顺便说一下,我的确尝试清除self.games
数组,并创建一个循环,将每个数组都打开并且不能解决问题。我仍然需要$scope.$apply()
才能更新DOM。
我对整个回购(连接指定的提交)可以在这里找到,如果有帮助:https://github.com/LukeSchlangen/solo_project/tree/df72ccc298524c5f5a7e63f4a0f9c303b395bafa
变化'无功自我=这一点;'到'无功自我= $范围;'应该更新您的阵列,'自我。游戏' – tsuz