我正在使用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