2015-07-20 43 views
0

我想將控制器範圍變量設置爲數據,但是沒有運氣。控制器中的console.log顯示未定義。感謝幫助!將Angularjs服務數據設置爲控制器變量

我的角度服務具有下面的代碼 -

service('VyrtEventService', ['$http', function($http) { 
    var events = []; 

    this.getArtistEvents = function(artistId) { 
    var url = '/api/users/' + artistId + '/'; 

    var promise = $http.get(url).success(function(data, status, headers, config) { 
     events = data.artist.events; 
     console.log(events); 
     return events; 
    }).catch(function(error) { 
     status = 'Unable to load artist data: ' + error.message; 
     console.log(status); 
    }); 

    return promise; 
    }; 
}]); 

,我在控制器如下引用它 -

VyrtEventService.getArtistEvents($scope.artistId).then(function(data){ 
    $scope.events = data.data.artist.events; 
}); 

console.log($scope.events); 
+0

你能顯示控制器代碼嗎? –

+0

控制器( 'VyrtEventCtrl',[ '$範圍', 'VyrtEventService',函數($範圍,VyrtEventService){ \t $ scope.artist; \t $ scope.events; \t $ scope.active_event_id; \t $ scope.status; \t VyrtEventService.getArtistEvents($ scope.artistId)。然後(功能(數據){ \t \t $ scope.events = data.data.artist.events; \t}); \t控制檯。 log($ scope.events); }]); – Yasir

+0

首先嚐試在聲明'$ scope.events = data.data.artist.events;中指定'$ scope.events = [];''確保您在'data.data.artist.events; ' –

回答

0

你應該只設置$scope.events = data在控制器中引起你的承諾已解決時返回data.artist.events

+0

不幸。 data.data.artist.events給了我一些東西,但是把它分配給$ scope.events,沒有。 – Yasir

0

將範圍從控制器中的任何位置傳遞到服務。確保你注入服務。

controllersModule.controller('MyCtrl', function($scope, $filter, $http, $compile, ngTableParams, **FactoryYouwant**) 
    { 

     **FactoryYouwant**.getdata($scope.**scopeYoutwantTopass**).then (function(responseData){  
     var ResponseFromServer =responseData.data; 
    } 

in service 

    controllersModule.factory('**FactoryYouwant**, function($http) { 
     var responseData = null; 

     return { 
      getdata : function(**data**){  (you dont have to use $)     
       responseData = $http.post or whatever actually gets you data; 
       return responseData; 
      } 

      }; 
    }); 

我希望這可以幫助你從控制器中任何地方的服務中調用數據。

+0

謝謝!目前正在注入 – Yasir

相關問題