meheshu
meheshu

Reputation: 31

Passing ui-router $stateParams to the $http factory service

I am trying to pass ui-router's $stateParams to the $httpd factory service via the controller. But i am clueless as to how to go about achieving the same. $http factory service does the role of fetching dynamic data based on the cid parameter. How do i pass this route parameter to the back-end script in the factory service.

Here is my code snippet.

.state('category',{url:'/category/:cid',templateUrl:'views/category.html',controller:'CategoryCtrl'})


myapp.factory('catService', function($http) {
   return {
     getCategory: function(callback) {
       $http.post('categorydetail.php').success(callback);
    }
   }
});

myapp.controller('CategoryCtrl', function($scope, catService) {
  catService.getCategory(function(data,status) {
     $scope.result = data;
  });
});

Would greatly appreciate your help. Thank you.

Upvotes: 3

Views: 2231

Answers (2)

GROX13
GROX13

Reputation: 4765

As I understand you need to access the $stateParams before the state is ready. You can not access the params for the state you are changing to with the $stateParams object until the state change is completed. When changing states several events happen from which first is $stateChangeStart where you are notified about changing state and can get all of the params in both states, so you can use the $stateChangeStart event to access the params and put them somewhere so you can access them when you need them.

myapp.run(['$rootScope', function($rootScope) {
    $rootScope.$on('$stateChangeStart', function (event, newState, newParams, oldState, oldParams) {
        $rootScope.newParams = newParams;
    });
}]);

myapp.factory('catService', function($http, $rootScope) {
   return {
     getCategory: function(callback) {
       $http.post('categorydetail.php?cid=' + $rootScope.newParams.cid).success(callback);
    }
   }
});

Upvotes: 0

wayne
wayne

Reputation: 3410

.state('category', {
        url:'/category/:cid',
        templateUrl:'views/category.html',
        controller:'CategoryCtrl'
 }
)

myapp.factory('catService', function($http) {
   return {
     getCategory: function(cid, callback) {
       $http.post('categorydetail.php?cid=' + cid).success(callback);
    }
   }
});

myapp.controller('CategoryCtrl', function($scope, $stateParams, catService) {
  catService.getCategory($stateParams.cid, function(data,status) {
     $scope.result = data;
  });
});

Upvotes: 4

Related Questions