使用Angular JS和Ionic动态插入JSON项

时间:2015-05-20 15:48:16

标签: javascript json angularjs

我一直在努力研究如何将JSON项插入动态列表中:

我有一个json文件,如下所示:

[
{
"id":"34",
"City":"New York",
"Country":"USA"
},
{
"id":"22",
"City":"Las vegas",
"Country":"USA"
},
{
"id":"44",
"City":"Paris",
"Country":"France"
},
{
"id":"45",
"City":"Lyon",
"Country":"France"
}
]

我想这样表达:

Screenshot

这是我的代码:

<div ng-controller="customersCtrl"> 
<div class="list">
<div ng-repeat="c in cities">
<div class="item item-divider" >
{{ c.Country }}
</div>
 <a class="item" href="#" ng-repeat="ci in cities" ng-if="c.Country == ci.Country"> {{ ci.City }} </a>
</div>

var app = angular.module('starter', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get('data.json')
       .then(function(result){
          $scope.cities = result.data;                
        });

});
它的表现如下:

enter image description here

2 个答案:

答案 0 :(得分:2)

最简单的方法是预处理数据以显示数据的固有结构。然后你可以使用嵌套的转发器。

&#13;
&#13;
angular.module('cityModule', []).
controller('CityController', ['$scope',
  function($scope) {
    var rawData = [{
      "id": "34",
      "City": "New York",
      "Country": "USA"
    }, {
      "id": "22",
      "City": "Las vegas",
      "Country": "USA"
    }, {
      "id": "44",
      "City": "Paris",
      "Country": "France"
    }, {
      "id": "45",
      "City": "Lyon",
      "Country": "France"
    }];

    $scope.citiesByCountry = {};
    
    for (var i = 0; i < rawData.length; i++) {
      var city = rawData[i];

      if ($scope.citiesByCountry[city.Country] == undefined) {
        $scope.citiesByCountry[city.Country] = {};
        $scope.citiesByCountry[city.Country].name = city.Country;
        $scope.citiesByCountry[city.Country].cities = [];
      }

      $scope.citiesByCountry[city.Country].cities.push(city);
    }

  }
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="cityModule">
  <div ng-controller="CityController">
    <div ng-repeat="(countryName, country) in citiesByCountry">
      <h1>{{country.name}}</h1>
      <div ng-repeat="city in country.cities">
        {{city.City}}
      </div>

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

答案 1 :(得分:1)

这是由于第一个循环,列表中有4个项目,并且没有任何逻辑可以阻止列表重复已经写入的国家。

<强>问题

<div ng-repeat="c in cities">
<div class="item item-divider" >
{{ c.Country }}

创建一个过滤器以循环显示唯一的Countries(这可能涉及创建新的唯一国家/地区列表)。

独特过滤器

app.filter('unique', function() {
   return function(collection, keyname) {
      var output = [], 
          keys = [];

      angular.forEach(collection, function(item) {
          var key = item[keyname];
          if(keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(item);
          }
      });

      return output;
   };
});
<div ng-repeat="c in cities | unique: 'Country'"></div>