Reputation: 10801
I'm trying to pass a parameter from the URL in the browser to a controller, for example, the 122 should be passed in $scope.id
in the controller so the JSON loaded is this http://52.41.65.211:8028/api/v1/categories/122/books.json
, not working though, any idea?
URL example http://www.example.com/categories/122
app.js
...
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
...
controller
app.controller('BookCategoryController', ['$scope', 'bookcategories', '$routeParams', function($scope, bookcategories, $routeParams) {
bookcategories.getAllBooks($scope.id).then(function(response) {
$scope.detail = response.data.books[$routeParams.categoryId];
});
}]);
service
app.service('bookcategories', ['$http', function($http) {
return {
getAllBooks: function(id) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
}
}
}]);
booksincategory.html
<div class="category col" ng-repeat="book in detail">
<h3 class="title">{{book.title}}</h3>
</div>
Upvotes: 1
Views: 1726
Reputation: 20006
If your URL is http://www.example.com/categories/122
and route params is like
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
then you will get the categoryId
in the controller as $routeParams.categoryId
Just set $scope.id = $routeParams.categoryId;
just set this in your controller before calling the service. So your controller will be like
app.controller('BookCategoryController', ['$scope', 'bookcategories', '$routeParams', function($scope, bookcategories, $routeParams) {
$scope.id = $routeParams.categoryId;
bookcategories.getAllBooks($scope.id).then(function(response) {
$scope.detail = response.data.books;
});
}]);
Just use
$scope.detail = response.data.books;
no need to use $scope.detail = response.data.books[$routeParams.categoryId]; its an incorrect syntax. Hope that will work for you. You have assigned $scope.detail incorrectly in your controller. I dint see any issue in the HTML
Upvotes: 1