2013-05-12 2 views
4

Я пытаюсь применить фильтр, используя флажки.Как использовать флажок, чтобы фильтровать результаты с помощью Angular?

Флажки показаны правильно:

<div data-ng-repeat="cust in customers"> 
    <input type="checkbox" data-ng-model="search.city" data-ng-true-value="{{ cust.city }}" data-ng-false-value=""/> {{ cust.city }} 
</div> 

но при проверке любого флажка, ничего не происходит:

<table> 

    <!-- table heading goes here --> 

    <tbody> 
     <tr data-ng-repeat="customer in customers | filter : search"> 
      <td > 
       {{ customer.firstName }} 
      </td> 
      <td > 
       {{ customer.lastName }} 
      </td> 
      <td > 
       {{ customer.address }} 
      </td> 
      <td > 
       {{ customer.city }} 
      </td> 
     </tr> 
    </tbody> 
</table> 

В таблице показаны все клиенты.

Что я хочу достичь: когда отмечены один или несколько флажков, таблица должна показывать только эти строки, которые соответствуют условию отмеченных флажков.

Что мне нужно сделать, чтобы заставить это работать?

ответ

3

Похоже, что вы предоставляете список клиентов, и когда выбран один или несколько, отобразите таблицу клиентов, которые находятся в том же городе, что и выбранные клиенты.

Для этого вам потребуется пользовательский фильтр:

// Define our filter 
app.filter('selectedCustomerCities', function($filter) { 
    return function(customers) { 
    var i, len; 

    // get customers that have been checked 
    var checkedCustomers = $filter('filter')(customers, {checked: true}); 

    // Add in a check to see if any customers were selected. If none, return 
    // them all without filters 
    if(checkedCustomers.length == 0) { 
     return customers; 
    } 

    // get all the unique cities that come from these checked customers 
    var cities = {}; 
    for(i = 0, len = checkedCustomers.length; i < len; ++i) { 
     // if this checked customers cities isn't already in the cities object 
     // add it 
     if(!cities.hasOwnProperty(checkedCustomers[i].city)) { 
     cities[checkedCustomers[i].city] = true; 
     } 
    } 

    // Now that we have the cities that come from the checked customers, we can 
    //get all customers from those cities and return them 
    var ret = []; 
    for(i = 0, len = customers.length; i < len; ++i) { 
     // If this customer's city exists in the cities object, add it to the 
     // return array 
     if(cities[customers[i].city]) { 
     ret.push(customers[i]); 
     } 
    } 

    // we have our result! 
    return ret; 
    }; 
}); 

Ваша разметка будет изменить во что-то вроде этого:

<div data-ng-repeat="customer in customers"> 
    <!-- record that this customer has been selected --> 
    <input type="checkbox" ng-checked="customer.checked" ng-model="customer.checked" /> {{ customer.city }} 
</div> 

<table> 
    <!-- table heading goes here --> 
    <tbody> 
     <!-- use our custom filter to only display customers from the cities selected --> 
     <tr data-ng-repeat="customer in customers | selectedCustomerCities"> 
      <td>{{ customer.firstName }}</td> 
      <td>{{ customer.lastName }}</td> 
      <td>{{ customer.address }}</td> 
      <td>{{ customer.city }}</td> 
     </tr> 
    </tbody> 
</table> 

Вы можете видеть, что работает в этом Plunker: http://plnkr.co/edit/GlHRLKECR4jeBS7Vf7TX?p=preview

+0

Это почти то, что я хочу. По умолчанию отображаются все клиенты. Когда флажок установлен для определенного города (или городов), фильтр применяется. – Martijn

+0

Я обновил свой ответ. Изменение было тривиальным: 'if (checkedCustomers.length == 0) {return customers; } 'в основном, возвращая всех клиентов, если ни один из них не был проверен. Надеюсь, что все имеет смысл для вас и дайте мне знать, если вам что-то объяснено. –

+0

Это именно то, что я хочу. Я понимаю почти каждый, кроме этого '$ filter ('filter') (клиенты, {checked: true});' Не могли бы вы объяснить это немного больше? – Martijn

7

Вы можете передать функцию в фильтр AngularJS. Например:

Набор Вы вводите тег как:

<input type="checkbox" ng-model="search[cust.city]" /> {{ cust.city }} 

Установите фильтр, как:

<tr data-ng-repeat="customer in customers | filter:searchBy() "> 

В контроллере:

function ctrl($scope) { 
    $scope.customers = [...]; 

    $scope.search = {};  
    $scope.searchBy = function() { 
    return function (customer) { 
     if ($scope.search[customer.city] === true) { 
     return true; 
     } 
    } 
    }; 
} 

Если вы хотите, чтобы показать всех клиентов при запуске просто инициализируйте $scope.search с city от customers.

Here is a sample Plunker.

+0

Мне нравится этот ответ намного лучше. Похоже, что это будет быстрее. – fauverism

+1

«Если вы хотите показать всех клиентов при запуске, просто инициализируйте $ scope.search с помощью города из массива клиентов». Не могли бы вы объяснить это чуть больше. любой пример для этого? –

+0

Это решение не группирует флажки, если 2 или более клиентов принадлежат одному и тому же городу – llermaly

Смежные вопросы