问题
I try to fetch JSON data on the page post/:postId within the following factory in my service:
angular.module('sampleapp.services', [])
.factory('DetailService', function($http) {
return {
getDetail: function(callback) {
$http.get('https://example.com/posts/' + $stateParams.postId + '.json').success(callback);
}
};
});
Unfortunately, $stateParams is undefined. What am I doing wrong? If I hardcode the URL, it works.
My routing:
.state('detail', {
url: '/post/:postId',
templateUrl: 'templates/detail.html',
controller: 'DetailCtrl'
})
and my controller:
.controller('DetailCtrl', function ($scope, DetailService) {
DetailService.getDetail(function(data) {
$scope.post = data;
});
});
My question is: How can i access the URL-paramters within my factory?
回答1:
Just like you inject the $http service, you must also inject the $stateParams service:
.factory('DetailService', function($http, $stateParams) {
来源:https://stackoverflow.com/questions/21799161/angularjs-stateparams-in-service