1

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>
4
  • A factory is supposed to return an object, which has methods that the users of the service can call. Your factory directly calls $http and returns a promise. Commented Sep 14, 2017 at 8:46
  • bookcategories should be a service. Btw. bookcategories is never used in your codes? Commented Sep 14, 2017 at 9:09
  • Use1937021, I see you don't like to mark "right answers". Please check all your questions and mark right answers. Thanks Commented Sep 14, 2017 at 9:16
  • Thanks m8, please check your other questions and mark right answers please. Commented Sep 14, 2017 at 9:40

1 Answer 1

1

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);
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

A factory is a wrong choice here and yet the code you posted is actually a factory disguised as a service. A real service would initialize this, and wouldn't return anything.

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.