6

I am following this question to filter ng-repeat by a field

ng-repeat :filter by single field

However my case is different, it's actually a field in the object value of the main object. Basically I want to show only data.a == 1

The following code works on the first list. The second list gives me error:

angular.module('myapp', [])
.controller('mainCtrl', function ($scope) {
    $scope.items = [{
        name: "John",
        data: {
            a: 1
        }
    }, {
        name: "Lee",
        data: {
            a: 2
        }
    }, {
        name: "Rue",
        data: {
            a: 3
        }
    }, {
        name: "Peter",
        data: {
            a: 1
        }
    }];
});

HTML

<div ng-controller="mainCtrl">
    <h1>List 1</h1>
    <p ng-repeat="item in items">{{ item.name }}</p>
    <h1>List 2</h1>
    <p ng-repeat="item in items | filter: {data.a :1}">{{ item.name }}</p>
</div>

http://plnkr.co/edit/nh4GryqZJbEiXSzMzTKk

Any help on how to do this or is there a nicer way?

UPDATE 1

I tried angular.filter filterBy and it didn't work either. Giving me blank array.

http://plnkr.co/edit/nh4GryqZJbEiXSzMzTKk?p=preview

    <p ng-repeat="item in items | filterBy: ['item.data.a'] :1">{{ item.name }}</p>

UPDATE 2

I tried this below

<p ng-repeat="item in items | filter: {data :{a:1}}">{{ item.name }}</p>

It seems to work but I need exact match, not substring match. I read this but not seem to find a way to add true AngularJS Filter Exact Match

Any clue?

UPDATE 3 (CORRECT ANSWER):

This works http://plnkr.co/edit/qJl6MtY6fOlVtD9Rv999?p=preview

Basically I added this to the controller

$scope.filteredItems = $filter('filter')($scope.items, {data :{a:1}}, true); 

and do ng-repeat on filteredItems instead. I don't see a way to pass true param in the view directly.

Community
  • 1
  • 1
HP.
  • 19,226
  • 53
  • 154
  • 253

2 Answers2

6

If you want to access the inner property you need to access it with object notation:

<p ng-repeat="item in items | filter: {data :{a:1}}">{{ item.name }}</p>

Check this plunker.

eladcon
  • 5,815
  • 1
  • 16
  • 19
  • Nice. This almost work but if I change a to 12 somewhere, it matches that also. How to match exact number? http://plnkr.co/edit/iBBq3x2HLUfbUBO3HUJJ?p=preview – HP. Mar 20 '15 at 01:28
  • 1
    I tried this `

    {{ item.name }}

    ` and it didn't work like it supposed to.
    – HP. Mar 20 '15 at 04:44
  • My final answer in UPDATE 3. Thanks. – HP. Mar 20 '15 at 04:54
3

If you are using \ can upgrade to angular 1.3, then you can use this: 1.3 filters These are faster. In particular, you can use filterBy

See: plunkr example

<p ng-repeat="item in items | filterBy: ['data.a'] :1">{{ item.name }}</p>

Otherwise, use a custom function. See my answer here: custom function

Community
  • 1
  • 1
trees_are_great
  • 3,881
  • 3
  • 31
  • 62