angularJS服务没有被调用

时间:2014-11-24 14:59:43

标签: angularjs

我对AngilarJS很新。我正在尝试在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>

声明“警告(品牌);”没有被召唤。这段代码有什么问题。是否缺少实施中的任何内容?

2 个答案:

答案 0 :(得分:0)

在服务中:

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

在控制器中:

   $scope.brandlist = BrandService.getBrands();
alert($scope.brandlist);

答案 1 :(得分:0)

.then次呼叫始终是异步的。这意味着,即使您在服务中执行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; } }); ,也无法将已解析的数据正确地返回到您的控制器中。您必须在控制器中编写它。

您的服务:

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

在您的控制器中:

dict