使用angularJS解析JSON

时间:2016-11-28 17:06:47

标签: angularjs json ionic-framework

这是我从API提供的JSON。正确生成JSON(使用cat变量属性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}
}

不需要显示第一个元素(api)。我只想要第二个(key: 0

我的工厂:

.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];
            }
        }
    }
}
})

我的控制器:

.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);
    })
})

简单的模板:

<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>

1 个答案:

答案 0 :(得分:1)

只需从对象中删除api属性:

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

顺便说一下,在你的模板中你可能有一个拼写错误:

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

应该是:

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