如何使用AngularJS过滤多个JSON数据



我的json文件

{
records: [
{
Name: "Alfreds Futterkiste",
City: "Berlin",
Country: "Germany"
},
{
Name: "Ana Trujillo Emparedados y helados",
City: "México D.F.",
Country: "Mexico"
},
{
Name: "Antonio Moreno Taquería",
City: "México D.F.",
Country: "Mexico"
},
{
Name: "Around the Horn",
City: "London",
Country: "UK"
}
]
}

如何使用国家/地区的"墨西哥"或"德国"的用户名称?

如果您关心性能,最好不要使用$filter提供商。相反,您应该选择自定义代码。

您应该更好地维护过滤记录的列表。

<div ng-controller="AppController as app">
  <label ng-repeat="country in app.availableCountries track by $index">
    <input type="checkbox" ng-model="country.selected" ng-click="app.filterByCountries()"> {{country.name}}
  </label>
  <h2>Filtered Records</h2>
  <div ng-repeat="record in app.filteredRecords">
    {{record | json}}
  </div>
</div>

并在控制器中执行过滤功能。

angular.module('app', [])
.controller("AppController", function() {
  this.records = [{
    Name: "Alfreds Futterkiste",
    City: "Berlin",
    Country: "Germany"
  }, {
    Name: "Ana Trujillo Emparedados y helados",
    City: "México D.F.",
    Country: "Mexico"
  }, {
    Name: "Antonio Moreno Taquería",
    City: "México D.F.",
    Country: "Mexico"
  }, {
    Name: "Around the Horn",
    City: "London",
    Country: "UK"
  }];
  this.filteredRecords = [];
  this.availableCountries = _.uniq(this.records.map(record => record.Country)).map(country => {
    return {
      name: country
    }
  });
  this.filterByCountries = () => {
    const lowerCaseCountries = this.availableCountries.filter(country => country.selected).map(country => country.name.toLowerCase());
    if (!lowerCaseCountries.length) {
      this.filteredRecords = angular.copy(this.records);
      return;
    }
    this.filteredRecords = angular.copy(this.records.filter(record => lowerCaseCountries.includes(record.Country.toLowerCase())));
  }
  this.filterByCountries();
})

这是一个工作的小提琴,展示了您的情况。随时提出任何要求。

尝试这个..

var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
$scope.data = records: [
{
Name: "Alfreds Futterkiste",
City: "Berlin",
Country: "Germany"
},
{
Name: "Ana Trujillo Emparedados y helados",
City: "México D.F.",
Country: "Mexico"
},
{
Name: "Antonio Moreno Taquería",
City: "México D.F.",
Country: "Mexico"
},
{
Name: "Around the Horn",
City: "London",
Country: "UK"
}
];
$scope.filteredData = $scope.data.filter(function(d) {
return d.Country === 'Mexico' || d.Country === 'Germany'
});
});

最新更新