问题
I know it have been asked here, but I'm still blocked with this issue where the result are not updating after i added a new data to the database.
I have one controller for adding and retrieving data
.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();
});
}]);
The broadcast event works fine and called the quizmaster.gameList() function to loads the game list after adding. The data that shows in the console is not updated and new created data isn't there yet. But when i take a look at my database, the newly added data is already stored. It just need to refresh the page to update the the lists. How can we reflect the added data in the view without refreshing the page?
Thanks for the help!
Update: Api.getGameList() is a service.
.factory('Api', function($http) {
return {
getGameList: function(params) {
return $http({
method : 'GET',
url : api + 'games/list',
params : params,
headers : {'X-GameApp-Token' : credential.token}
});
}
}
});
回答1:
What is Api.getGameList()? If it is done outside of angular (i.e. the then() isn't from an $http promise) then you have to notify angular of your changes. Wrap setting the data in a $scope.apply():
$scope.$apply(function() {
scope.games = result.data;
});
来源:https://stackoverflow.com/questions/19396040/angularjs-result-is-not-updating-when-new-create-data-has-been-added