ng-repeat :filter by single field

后端 未结 12 2100
栀梦
栀梦 2020-11-22 10:06

I have an array of products that I\'m repeating over using ng-repeat and am using

<
相关标签:
12条回答
  • 2020-11-22 10:38

    Be careful with angular filter. If you want select specific value in field, you can't use filter.

    Example:

    javascript

    app.controller('FooCtrl', function($scope) {
       $scope.products = [
           { id: 1, name: 'test', color: 'lightblue' },
           { id: 2, name: 'bob', color: 'blue' }
           /*... etc... */
       ];
    });
    

    html

    <div ng-repeat="product in products | filter: { color: 'blue' }"> 
    

    This will select both, because use something like substr
    That means you want select product where "color" contains string "blue" and not where "color" is "blue".

    0 讨论(0)
  • 2020-11-22 10:39

    Search by color:

    <input type="text" ng-model="searchinput">
    <div ng-repeat="product in products | filter:{color:searchinput}">
    

    you can do an inner nest too.

    filter:{prop1:{innerprop1:searchinput}}
    
    0 讨论(0)
  • 2020-11-22 10:47

    You must use filter:{color_name:by_colour} instead of

    filter:by_colour
    

    If you want to match with a single property of an object, then write that property instead of object, otherwise some other property will get match.

    0 讨论(0)
  • 2020-11-22 10:55

    If you want to filter on a grandchild (or deeper) of the given object, you can continue to build out your object hierarchy. For example, if you want to filter on 'thing.properties.title', you can do the following:

    <div ng-repeat="thing in things | filter: { properties: { title: title_filter } }">
    

    You can also filter on multiple properties of an object just by adding them to your filter object:

    <div ng-repeat="thing in things | filter: { properties: { title: title_filter, id: id_filter } }">
    
    0 讨论(0)
  • 2020-11-22 10:58

    You can filter by an object with a property matching the objects you have to filter on it:

    app.controller('FooCtrl', function($scope) {
       $scope.products = [
           { id: 1, name: 'test', color: 'red' },
           { id: 2, name: 'bob', color: 'blue' }
           /*... etc... */
       ];
    });
    
    <div ng-repeat="product in products | filter: { color: 'red' }"> 
    

    This can of course be passed in by variable, as Mark Rajcok suggested.

    0 讨论(0)
  • 2020-11-22 10:58

    Best way to do this is to use a function:

    html

    <div ng-repeat="product in products | filter: myFilter">
    

    javascript

    $scope.myFilter = function (item) { 
        return item === 'red' || item === 'blue'; 
    };
    

    Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.

    0 讨论(0)
提交回复
热议问题