bklups
bklups

Reputation: 300

Parse JSON with angularJS

Here is my JSON which provides from an API. JSON is correctly generated (with a cat variable attribute url)

{
"api":
  {"version":"1.0",
   "url":"http:\/\/www.example.com",
   "encoding":"UTF-8",
   "generated":"2016-11-28T15:12:18+01:00",
   "contents":"categories_hierarchical"},
"0":{"id":"46",
     "name":"Music",
     "parent_id":"56",
     "event_count":"411",
     "rank":1}
}

First element (api) doesn't need to be displayed. I just want the second (key: 0)

My factory :

.factory('selectedCategoriesService', function($http, $stateParams) {
        var selectedCategories = [];

        return {
        getselectedCategories: function(){
            return $http.get('http://www.myapi.com&data=categorie', { params: { cat: $stateParams.id } }).then(function(response){
                selectedCategories = response.data;
                return response.data;
            });
        },
    getselectedCategorie: function(selectedCategorieId){
        for(i=0;i<selectedCategories.length;i++){
            if(selectedCategories[i].id == selectedCategorieId){
                return selectedCategories[i];
            }
        }
    }
}
})

My controller :

.controller('CategoriesListDetailCtrl',function($scope, $stateParams, selectedCategoriesService){

    var selectedCategorieId = $stateParams.id;
    $scope.selectedCategorie = selectedCategoriesService.getselectedCategorie(selectedCategorieId);

  selectedCategoriesService.getselectedCategories().then(function(selectedCategories){
  $scope.selectedCategories = selectedCategories;
  console.log($scope.selectedCategories);
    })
})

The simple template :

<ion-pane>

  <ion-view view-title="{{selectedCategorie.name}}">

    <ion-content class="has-header">

        <ion-item class="item-thumbnail-left">

           <h2>{{selectedCategories.id}}</h2>

        </ion-item>

    </ion-content>

  </ion-view>

</ion-pane>

Upvotes: 0

Views: 68

Answers (1)

lucasnadalutti
lucasnadalutti

Reputation: 5958

Just remove the api property from the object then:

selectedCategories = response.data;
delete selectedCategories.api;
return response.data;

By the way, in your template you probably have a typo:

<h2>{{selectedCategories.id}}</h2>

should probably be:

<h2>{{selectedCategorie.id}}</h2>

Upvotes: 1

Related Questions