selanac82
selanac82

Reputation: 3000

Force angular scope to update from service

I've create an angular controller and service. In my service I have an array that starts off blank when the app loads, but is filled later on. In my controller I have a property on $scope that points to that array. When the array in the service is updated I assumed the $scope property would also be updated and the DOM would update accordingly. Here is the sample code.

app.controller("myCtlr", ["$scope", "$service", function($scope, $service){

   $scope.friends = $service.friends

}]);

app.factory("$service", function($http){

   var friends = {};

   friends = {

      get: function(){
        $http.get("/someurl").success(function(data){

           // data is the array of friends
           friends = data; 

        });           
      }

   };



});

I've tried using angular.extend but there aren't many good example of it online so I don't fully understand it yet. Any help is much appreciated. Thanks!

Upvotes: 0

Views: 582

Answers (1)

tymeJV
tymeJV

Reputation: 104775

Angular $http automatically kicks off a digest cycle, you should also return friends from your service and also use .then to continue the promise pattern:

app.factory("$service", function($http){

    var friends = {};

    friends = {

    get: function(){
        $http.get("/someurl").then(function(data){
            return data.data
        });    
    }

    return friends;
});

And in your controller:

$service.friends.get().then(function(data) {
    console.log(data);
});

Upvotes: 2

Related Questions