简体   繁体   中英

How to filter data based on drop down menu value?

Note: AngularJS version 1.2.28

I am a newbie to AngularJS and trying to hide elements based on the value chosen in a drop down menu. If the drop down option of "Black" is selected, the data table should only show elements with a division color of "Black". If the drop down option of "Yellow" is selected, the data table should only show elements with a division color of "Yellow".

How would I go about filtering data and hide the items that do not contain the value selected in the drop down menu?

Here's my sample data ( I left out the app and controller directive for brevity ):

[{ lastName: 'Doe', firstName: 'John', division: 'Blue'}, 
{ lastName: 'Smith', firstName: 'Jane', division: 'Yellow' }]

Drop Down HTML:

<select ng-model="orderProp">
    <option value="division">Black</option>
    <option value="division">Yellow</option>
</select>

Table View:

<table>
    <thead>
    ...snip ...
    </thead>
</table>
<tbody>
    <tr ng-repeat="item in items | orderBy: orderProp">
        <td></td>
    </tr>
</tbody>

My script:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope, $http){
    $http.get('data.json').success(function(data){
        $scope.items = data;
        $scope.orderProp = 'lastName';
    });
});

The answer is simple, you should add default filter like you added orderBy (which is also some kind of filter):

<table>
    <thead>
    ...snip ...
    </thead>
</table>
<tbody>
    <tr ng-repeat="item in items | filter: orderProp | orderBy: orderProp">
        <td></td>
    </tr>
</tbody>

HERE you can find more about filter function.

Try this,

<tr ng-repeat="item in items | filter: {division: orderProp}">
    <td></td>
</tr>

and why do you need $scope.orderProp = 'lastName'; in controller? Remove it if not really needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM