user2322274 user2322274 - 1 year ago 54
AngularJS Question

How to assign value returned by service's $http.get() to a variable in controller?

I have created the separate service for fetching data from server, but I want to assign the data that this service returns to variable in the controllers. in this case data is a simple JSON file.

Here is my service

.service('TextService', ['$http', function CompanyService($http) {
var service = {};
then(function (response) {
service.text =;
}, function (response) {

return service;

and here is my controller

app.controller("myCtrl", ['$scope', 'TextService', function($scope, TextService){

$scope.text = TextService.text;


then I try to display $scope.text, but it does not work. (I have controller assigned in html)

<div class="content">

I guess I will need to use some helper function since, TextService is asynchronous. I would love to understand how to make it work and why it is not working now. and is it a good structure to wrap $http call in service?

Answer Source

Your service must provide methods to get text :

.service('TextService', ['$http', '$q', function CompanyService($http, $q) {
    var text;
    var service = {
      getText: function() {
          var defered = $q.defer();
          if(text == undefined) {
            $http.get('text.json').then(function success(data) {
              text = data.text;
             function error(err) { defered.reject(err) });
           else {
           return defered.promise;
  return service;

And your controller call the service :

app.controller("myCtrl", ['$scope', 'TextService', function($scope,    TextService){
 TextService.getText().then(function(text) { $scope.text = text } );