user1937021
user1937021

Reputation: 10811

AngularJS - Dynamic parameter in $http URL

The URL I use to retreive a JSON for my app has a dynamic parameter (:id ). I'm not too sure how I can work with this, so that it passes the ID the user has chosen. Just need a bit of guidance.

app.factory('bookcategories', ['$http', function($http) {
  return $http.get('http://52.41.65.211:8028/api/v1/categories/:id/books.json')
    .success(function(data) {
        return data;
    })
    .error(function(err) {
        return err;
  });
}]);

Controller

app.controller('BookCategoryController', ['$scope', 'categories', '$routeParams',  function($scope, categories, $routeParams) {
    categories.success(function(data) {
    $scope.detail = data.categories[$routeParams.bookId];
    $scope.currentCategoryIndex = parseInt($routeParams.categoryId);

        $scope.myCategoriesDetails = $scope.category;
    });
}]);

app.js

...
  .when('/categories/:categoryId', {
    controller: 'BookCategoryController',
    templateUrl: 'views/booksincategory.html'
})
...

HTML

<h3 class="title">{{book.title}}</h3>

Upvotes: 1

Views: 78

Answers (1)

lin
lin

Reputation: 18402

You could achieve this with a little service like the following code example. A factory is a wrong choice here.

app.service('bookCategories', ['$http', function($http) {
  this.get = function (id) {
      return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
        .success(function(data) {
          return data;
        })
        .error(function(err) {
          return err;
        });
  };
}]);

And than use it like:

app.controller('MyCtrl', function(bookCategories) {
  bookCategories.get(1).then(function (result) {
    console.log(result);
  });
});

Upvotes: 1

Related Questions