Modelesq
Modelesq

Reputation: 5402

Angular JS: retrieve json data based on id

I have a list of items. When you click on an item it recognizes its id and takes you to its corresponding page localhost:8000/products/1.

But how do I get the rest of the information just for that one product/item id?

My json data looks like this...

[
  {
    "id": "1",
    "title": "Chips",
    "subTitle": "Snack",
    "imgUrl": "chips.png",
    "demoImgUrl": "snacks.png",
    "brandLogoUrl": "somebrand.png"
  },
...

my productList.js where it successfully shows the list of products

(function() {

  'use strict';

  angular
    .module('testProducts')
    .component('productList', {
      templateUrl: '/components/productList/productList.html',
      controller: ProductListController
    });

  ProductListController.$inject = ['ProductsService'];

  function ProductsListController(ProductsService) {
    var vm = this;

    vm.products = [];

    // Get the Products data
    ProductService.getData().then(function(response) {
      console.log(response.data);
      vm.products = response.data;
    }).catch(function(err) {
      console.error('Error', err);
    });
  }

})();

and my item.js where it should grab the json for that one id

(function() {

  'use strict';

  angular
    .module('testProducts')
    .controller('itemController', ItemController);

  ItemController.$inject = ['$state', '$stateParams', 'ProductsService'];

  function ItemController($state, $stateParams, ProductsService) {
    var vm = this;

    vm.itemId = $stateParams.itemId;
    console.log($stateParams.itemId);

    // Get the Product data
    ProductsService.getData().then(function(response) {
       console.log(response.data);
    }).catch(function(err) {
       console.error('Error', err);
    });
  }

})();

And my html item.html (which does not render title or imgUrl)

<div>
  <p>itemId: {{$ctrl.itemId}}</p>
  <p>{{$strl.title}}</p>
  <img src="{{$ctrl.imgUrl}}" />
</div>

I've gotten

angular.js:13236 ReferenceError: ProductService is not defined

So how do I just display the information based on the json data item id?

Upvotes: 2

Views: 158

Answers (1)

Rakesh Nalumachu
Rakesh Nalumachu

Reputation: 218

You can use $filter to retrieve desired object based using any property. Its syntax is $filter('filter')(vm.products, { Id: 1 }). vm.products is the data nothing but list of objects and it will return list of all objects which has Id 1.

Upvotes: 1

Related Questions