2014-11-24 68 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); 
    }); 
});