0

I'm very new to AngilarJS. I am trying to write a service in angularJS.

<script>
var module = angular.module("myapp", []);

module.service('BrandService', function ($http) {

    var brands = [];

    this.getBrands = function()
    {
        return $http.get('http://admin.localhost/cgi-bin/brand.pl')
            .then(function(response) 
            {
                brands = response.brands;
                alert (brands);
            });
    }

    //simply returns the brands list
    this.list = function () 
    {
        return brands;
    }


});

module.controller("brandsController", function($scope, BrandService) {
    $scope.brandlist = BrandService.list();
    alert ($scope.brandlist);
});

</script>

The statement "alert (brands);" is not getting called. What is the issue with this code. Is m missing any thing in implementation?

Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131

2 Answers2

0

In service:

this.getBrands = function() {
  $http.get('http://admin.localhost/cgi-bin/brand.pl').then(function(response) {
    brands = response.brands;
    alert(brands);
    return brands;
  });
}

In controller:

   $scope.brandlist = BrandService.getBrands();
alert($scope.brandlist);
CozyAzure
  • 8,280
  • 7
  • 34
  • 52
Sreehari S
  • 388
  • 1
  • 12
0

$http calls are always async. Meaning, even you do a .then at your service, there is no way it will properly the resolved data back into your controller. You will have to write it in your controller.

Your Service:

module.service('BrandService', function($http) {
  var brands = [];
  this.getBrands = function() {
    //do not need the dot then.
    return $http.get('http://admin.localhost/cgi-bin/brand.pl')
  }
  //simply returns the brands list
  this.list = function() {
    return brands;
  }
});

In your controller:

module.controller("brandsController", function($scope, BrandService) {
  BrandService.list()
    .then(function(response) {
      $scope.brandlist = response.brands;
      alert($scope.brandlist);
    });
});
CozyAzure
  • 8,280
  • 7
  • 34
  • 52