Фильтрация сложного объекта внутри вложенного ng-repeat
Я хочу фильтровать объект внутри вложенного ng-repeat.
HTML:
<div ng-controller="MyController">
<input type="text" ng-model="selectedCityId" />
<ul>
<li ng-repeat="shop in shops">
<p ng-repeat = "locations in shop.locations | filter:search" style="display: block">
City id: {{ locations.city_id }}
<span style="padding-left: 20px; display: block;" ng-repeat="detail in locations.details | filter:item">Pin code: {{detail.pin}}</span>
</p>
</li>
</ul>
Контроллер:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.search = function (location) {
if ($scope.selectedCityId === undefined || $scope.selectedCityId.length === 0) {
return true;
}
if (location.city_id === parseInt($scope.selectedCityId)) {
return true;
}
};
$scope.item = function (detail) {
if ($scope.selectedCityId === undefined || $scope.selectedCityId.length === 0) {
return true;
}
if (detail.pin == parseInt($scope.selectedCityId)) {
return true;
}
};
$scope.shops =
[
{
"category_id":2,
"locations":[
{
"city_id":368,
"details": [{
"pin": 627718,
"state": 'MH'
}]
}
]
},
{
"name":"xxx",
"category_id":1,
"locations":[
{
"city_id":400,
"region_id":4,
"details": [{
"pin": 627009,
"state": 'MH'
},{
"pin": 129818,
"state": 'QA'
}]
},
]
},
];
});
Здесь скрипка:
http://jsfiddle.net/suCWn/210/
Я хочу использовать несколько фильтров внутри ng-repeat.
Пример: каждый раз, когда пользователь вводит идентификатор в поле ввода. Список должен фильтроваться на основе cityID или PinCode.
если пользователь вводит "129818", он должен показать результат PIN-кода 129818 вместе с его родительским идентификатором города
Аналогично, если пользователь вводит 400, список должен фильтровать и отображать результат cityID с 400 вместе с его дочерним кодом.
EDIT:
Обновить код http://codepen.io/chiragshah_mb/pen/aZorMe?editors=1010]
Ответы
Ответ 1
Во-первых, вы не должны фильтровать местоположения с соответствующими деталями. Используйте что-то вроде этого в фильтре search
:
$scope.search = function (location) {
var id = parseInt($scope.selectedCityId);
return isNaN(id) || location.city_id === id ||
location.details.some(function(d) { return d.pin === id });
};
Чтобы отобразить детали, если они были отфильтрованы по идентификатору cityID, вы должны найти родителя location
и проверить, не отфильтрован ли он.
$scope.item = function (detail) {
var id = parseInt($scope.selectedCityId);
return isNaN(id) || detail.pin === id || locationMatches(detail, id);
};
function locationMatches(detail, id) {
var location = locationByDetail(detail);
return location && location.city_id === id;
}
function locationByDetail(detail) {
var shops = $scope.shops;
for(var iS = 0, eS = shops.length; iS != eS; iS++) {
for(var iL = 0, eL = shops[iS].locations.length; iL != eL; iL++) {
if (shops[iS].locations[iL].details.indexOf(detail) >= 0) {
return shops[iS].locations[iL];
}
}
}
}
EDIT Другое, более гибкое решение - удалить все фильтры из ngRepeats и выполнить фильтрацию в методе, который вы вызываете в ngChange текста поиска. Вот базовая структура этого подхода.
myApp.controller('MyController', function($scope, $http) {
var defaultMenu = [];
$scope.currentMenu = [];
$scope.searchText = '';
$http.get(/*...*/).then(function (menu) { defaultMenu = menu; } );
$scope.onSearch = function() {
if (!$scope.searchText) {
$scope.currentMenu = defaultMenu ;
}
else {
// do your special filter logic here...
}
};
});
И шаблон:
<input type="text" ng-model="searchText" ng-change="onSearch()" />
<ul>
<li ng-repeat="category in currentMenu">
...
</li>
</ul>
Ответ 2
Я обновил свои фильтры. Проблема в вашем фильтре search
, который вы проверяете только для city_id, что вам нужно сделать:
- Убедитесь, что введенный идентификатор - city_id
- Проверьте, является ли типизированный идентификатор
pid
дочерней детали заданного местоположения
Аналогичная вещь для фильтра item
:
- Проверьте, является ли типизированный идентификатор
pid
фильтруемой детали
- Проверьте, является ли типизированный идентификатор
city_id
родительского расположения детали, переданной в
Вот рабочий jsFiddle. Надеюсь, это поможет.
Ответ 3
Просто изменив JSON
, чтобы включить city_id
для детей, поэтому вам не нужно перебирать его, чтобы получить родительский city_id
, решение так же просто:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.search = function (location) {
if (!$scope.selectedCityId)
return true;
//if user input is contained within a city id
if (location.city_id.toString().indexOf($scope.selectedCityId) > -1)
return true;
for (var i = 0; i < location.details.length; i++)
//if user input is contained within a city pin
if (location.details[i].pin.toString().indexOf($scope.selectedCityId) > -1)
return true;
};
$scope.item = function (detail) {
if (!$scope.selectedCityId)
return true;
//if user input is contained within a city id
if (detail.city_id.toString().indexOf($scope.selectedCityId) > -1)
return true;
//if user input is contained within a city pin
if (detail.pin.toString().indexOf($scope.selectedCityId) > -1)
return true;
};
Измененный JSON
$scope.shops=[{"category_id":2,"locations":[{"city_id":368,"details":[{"city_id":368,"pin":627718,"state":'MH'}]}]},{"name":"xxx","category_id":1,"locations":[{"city_id":400,"region_id":4,"details":[{"city_id":400,"pin":627009,"state":'MH'},{"city_id":400,"pin":129818,"state":'QA'}]},]},];});
Если прямое изменение JSON
невозможно, вы можете изменить его следующим образом в этом контроллере непосредственно после этого оператора $scope.shops = ...json...
:
for(var i=0; i<$scope.shops.length; i++)
for(var j=0, cat=$scope.shops[i]; j<cat.locations.length; j++)
for(var k=0, loc=cat.locations[j]; k<loc.details.length; k++)
loc.details[k].city_id=loc.city_id;
Рабочая скрипка:
http://jsfiddle.net/87e314a0/
Ответ 4
Я попытался сделать решение более понятным:
index.html:
<div ng-controller="MyController">
<input type="text" ng-model="search.city_id" />
<ul>
<li ng-repeat="shop in shops">
<p ng-repeat = "locations in shop.locations | filter:search.city_id" style="display: block">
City id: {{ locations.city_id }}
<span style="padding-left: 20px; display: block;" ng-repeat="detail in locations.details | filter:item">Pin code: {{detail.pin}}</span>
</p>
</li>
</ul>
</div>
app.js:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.shops =
[
{
"category_id":2,
"locations":[
{
"city_id":368,
"details": [{
"pin": 627718,
"state": 'MH'
}]
}
]
},
{
"name":"xxx",
"category_id":1,
"locations":[
{
"city_id":400,
"region_id":4,
"details": [{
"pin": 627009,
"state": 'MH'
},{
"pin": 129818,
"state": 'QA'
}]
},
]
},
];
});
Здесь скрипка:
mySolution