如何从JSON文件中重复不同的对象

时间:2015-12-14 12:05:00

标签: javascript angularjs json

我已经编辑了我的问题。希望你们现在能理解:D 我想说的是我有一个名为data.json的文件,在那个文件中我有这些数据' s:

{
"FOOD": [{
     "item_name": "Starter"
}],
"DRINKS": [{
     "item_name": "COKE"
}]
}

我在app.js中编写了代码

app.controller('DataCtrl', ['$scope', '$state', '$http', 
     function($scope, $state, $http) {$http.get('js/data.json').success ( function(data) {
    $scope.FOOD = data.FOOD;
    $scope.DRINKS = data.DRINKS;
}) 

}]);

details.html

<ion-view view-title="Menus">
  <ion-content ng-controller="DataCtrl">
    <ion-item ng-repeat="i in FOOD" class="item-thumbnail-left item-text-wrap item-icon-right">
       <h2 class="title">{{i.item_name}}</h2>
    </ion-item>
  </ion-content>
</ion-view>

我可以从食物中提取所有数据,但我想要的是我想动态更改FOOD n DRINKS之间的数据。当有人点击它应该显示食物数据的食物时,当有人点击我想要的饮料{{1应该改为ng-repeat="i in FOOD"。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

我完全不明白你的问题。可能这段代码会帮助你。

当有人点击FOOD(参数=&#39; FOOD&#39;)时,$scope.array会使用FOOD数据填充,当有人点击DRINKS时(参数=&#39;饮品&#39; ),使用DRINKS数据填充$scope.array

<强>控制器

app.controller('myCtrl', function($scope) {
    $scope.parameter = "DRINKS";
    $scope.data = {
        "FOOD": [{
            "item_name": "Starter"
        }],
        "DRINKS": [{
            "item_name": "COKE"
        }]
    }
    $scope.FOOD = $scope.data.FOOD;
    $scope.DRINKS = $scope.data.DRINKS;
    if ($scope.parameter == 'FOOD') $scope.array = $scope.FOOD;
    else $scope.array = $scope.DRINKS;
});

<强>模板

<ion-view view-title="Menus">
  <ion-content ng-controller="DataCtrl">
    <ion-item ng-repeat="i in array" class="item-thumbnail-left item-text-wrap item-icon-right">
       <h2 class="title">{{i.item_name}}</h2>
    </ion-item>
  </ion-content>
</ion-view>

Stack Overflow Demo

&#13;
&#13;
var app = angular.module('myApp', ['ngRoute']);
app.controller('myCtrl', function($scope) {
  $scope.parameter = "DRINKS";
  $scope.data = {
    "FOOD": [{
      "item_name": "Starter"
    }],
    "DRINKS": [{
      "item_name": "COKE"
    }]
  }
  $scope.FOOD = $scope.data.FOOD;
  $scope.DRINKS = $scope.data.DRINKS;
  if ($scope.parameter == 'FOOD') $scope.array = $scope.FOOD;
  else $scope.array = $scope.DRINKS;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="i in array">
    {{i.item_name}}
  </div>

</div>
<script>
</script>
&#13;
&#13;
&#13;