1

I need to update view when new data created at server? How to do this correct?

My controller

app.controller('MainController', ['$scope', 'games', function($scope, games) {
games.success(function(data) {
    console.log(data[0]);
    $scope.games = data[0];
}); 
}]);

My factory

app.factory('games', ['$http', function($http) {


return $http.get('./game')
     .success(function(data) {
       return data;
     })
     .error(function(data) {
       return data;
     });
}]);
2
  • Might want to look into web socket if the back end need to be able to notify the front end without being queried like in a normal RESTful request. Commented Sep 11, 2015 at 15:48
  • Web Sockets is the answer! socket.io Commented Sep 11, 2015 at 15:51

2 Answers 2

2

Remember that services in Angular are objects. So create a simple method that returns a promise, to manage it in the controller.

Controller

app.controller('MainController', ['$scope', 'games', function($scope, games) {

        games.get().then(function(data) {
            console.log(data[0]);
            $scope.games = data[0];
        });

    }]);

Service

app.service('games', ['$http', function($http) {

    this.get = function() {
        return $http.get('./game');
    };

}]);
Sign up to request clarification or add additional context in comments.

3 Comments

Provider 'games' must return a value from $get factory method.
Sorry, you are right. I forgot to change 'factory' to 'service'. Let me know if it works!
I have changed the answer. Check it out.
1

you can use $timeout if you do not wish to use websockets

$timeout(function(){
  games.success(function(data) {
    console.log(data[0]);
    $scope.games = data[0];
 }); 
},1000);

Update : sorry it should be $interval

$interval(function(){
  games.success(function(data) {
    console.log(data[0]);
    $scope.games = data[0];
 }); 
},1000);

Update : how to do this using factory

app.factory('games', ['$http', function($http) {
    return {
        getGame: function() {
            return $http.get('./game');
        }
    }
}]);

Now in your controller

app.controller('MainController', ['$scope', 'games', function($scope, games) {
    games.getGame().success(function(data) {
        $scope.games = data[0];
    });
}]);

4 Comments

what problem do you came across while using $timeout..?
Same result, i need to refresh page to see new data.
i thought you want to change data in realtime nevermind let me put the code of how you do the same thing with factory
I add $interval to get method in Controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.