2014-11-24 72 views
0

我是AngilarJS的新手。我正在尝试在angularJS中编写一个服务。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> 

声明“alert(brands);”没有被调用。这段代码有什么问题。 m是否在执行中缺少任何东西?

+0

警报是空的或不提醒? – 2014-11-24 15:01:39

+0

不在服务中提醒并在控制器中提醒空。 – 2014-11-24 15:04:08

+0

打开调试控制台,告诉我们错误信息是什么。 – 2014-11-24 15:06:33

回答

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); 
0

$http调用总是异步。这意味着,即使您为您服务,也无法将解决的数据正确地返回到您的控制器中。你将不得不把它写在你的控制器中。

您服务:

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); 
    }); 
});