Angularjs; use $http in service returns reference instead of actual data

angularjs, angularjs-scope, object, this

Solution

You can use a watch to make this work (see plunker)

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,cityService) {
  //$scope.cities = [];
  $scope.service = cityService;
  cityService.initCities();


  $scope.$watch('service.getCity()', function(newVal) {
    $scope.cities = newVal;
    console.log(newVal)
  });


});

app.service('cityService', function($http) {
  var that = this;
  this.cities = [];

  this.initCities = function() {
      $http.get('data.js').success(function(data) {
          that.cities = data.cities;
      });
  };

  this.getCity = function() {
      return this.cities;
  };
});

Problem

I'm using the services directive in Angularjs not factory and I need to populate a json file to local variable; ``` /* Contains projects on the town */ leMaireServicess.service('cityService', function($http) { // JSON regions and cities loader this.cities = []; // initCities this.initCities = function() { this.cities = $http.get('data/census/cities.js').success(function(data) { return data; }); return this.cities; }; // Get city info this.getCity = function() { return this.cities; }; }); ``` And in my controller I have ``` // Saved game controller leMaireControllers.controller('GameCoreCtrl', function($scope, cityService) { /* Control the town project slides */ cityService.initCities(); $scope.city = cityService.getCity(); console.log($scope.city); }); ``` But instead of returning the actual data, it returns; ``` Object {then: function, catch: function, finally: function, success: function, error: function} ```

Original source

Related problems