How do I obtain $stateParams in Angular sevice


#1

Here is my state definition:

.state('sub-topic',{
    url:"/topics/:topicId",
    templateUrl: "templates/sub-topics.html",
    controller: "SubTopicsController"
})

Here is my service

myApp.service('subTopicsService',function($http, $stateParams){

    this.getSubTopics = function(){
        $http.get('topics/' + $stateParams.topicId + '.json').success(function(data, status, header, config) {
             return data;
        });
    }
})

A part of my controller, that has 'subTopicService' injected

$scope.topicList = subTopicsService.getSubTopics();

The problem is, the $stateParams is undefined in the service. Specifically I get this error message:

Cannot access property :topicId of undefined.
How do I use $stateParams in my service?


Calling wcf in factory?
#2

You have to pass it from controller, try it:

myApp
  .service('subTopicsService',function($http){

this.getSubTopics = function(paramsFromCtrl) {
    $http.get('topics/' + paramsFromCtrl.topicId + '.json').success(function(data, status, header, config) {
         return data;
    });
}})

and in controller:

$scope.topicList = subTopicsService.getSubTopics($stateParams);

#3

Sweet. That is really simple.