I am making a call an http call to a json file. In the first controller I get the categories , and in the second controller I get the category with a certain ID.
The url gets updated with an categoryid but the $routeParams is shown undefined and cannnot access the file.
Here is my code:
$stateProvider.state('categories', {
url: '/category',
templateUrl: 'templates/categories.html',
controller: 'CategoriesCtrl'
});
$stateProvider.state('postC', {
url: '/category/:category',
templateUrl: 'templates/postsc.html',
controller: 'PostCtrl'
});
In the controller I have the following:
angular.module('myapp')
.controller('CategoriesCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get("~/wp/v2/terms/category")
.then(function(res) {
$scope.categories = res.data;
})
}
])
.controller('PostCtrl', ['$scope', '$http', '$routeParams',
function($scope, $http, $routeParams) {
$http.get("~/wp/v2/terms/category/" + $routeParams.category).success(function(res) {
$scope.current_category_id = $routeParams.category;
console.log($routeParams.category);
$scope.pageTitle = 'Posts in ' + res.data.name + ':';
document.querySelector('title').innerHTML = 'Category: ' + res.data.name + ' | AngularJS Demo Theme';
$http.get("~/wp/v2/posts/?filter[category_name]=" + res.data.name).success(function(res) {
$scope.posts = res.data;
console.log($scope.posts);
})
})
}
]);
The view for the categories is the following:
<div class="list">
<a ng-repeat="category in categories" href="#/category/{{category.id}}" class="item item-thumbnail-left">
<h2>{{category.name}}</h2>
</a>
</div>
And when I click on the category the URL becomes: http://localhost:8100/#/category/12, but the $stateparams.category in ~/wp/v2/terms/category/" + $routeParams.category
is undefined therefor the http request cannot go through.
I cannot figure it out what am I missing ?
Try changing
$routeParams
with$stateParams
in every instance. You’re obviously usingui-router
which uses “states”, whilengRouter
uses “routes”.You might want to double-check the code near
it should be
Read more here on syntax of creating a Controller. You are missing injectors.