1

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>
1
  • 1
    Did you get chance to look at this answer? I don't understand why you're opening multiple question.. Rather concentrate on single and fix it at one place :) Commented Sep 14, 2017 at 13:45

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

makes sense but nothing appears still, it seems to call the JSON correctly now, is there something wrong in my HTML?
@user1937021 use $scope.detail = response.data.books; you had used an incorrect syntax. Hope that will work for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.