Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'anyPropertyKey' in Angular filter definition?

Tags:

angularjs

Angular JS

{{ filter_expression | filter : expression : comparator : anyPropertyKey}}

I am unable to understand the last argument i.e., anyPropertyKey. Can anybody please explain me with a simple example

<div ng-init="ar=[{n:'ram1', m:1}, {n:'mah', m:1}, {n:'vij', m:3}]">
    <div ng-repeat='x in ar | filter: "1": false: propertyName'>{{x}}</div>
</div>

this is what I tried so far. In the above code what I should write instead of propertyName.

like image 364
Mr_Perfect Avatar asked Jul 27 '16 06:07

Mr_Perfect


People also ask

How do you filter NG repeat?

The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.

What is custom filter in AngularJS?

Introduction to AngularJS Custom Filter. In AngularJS filters are used to modify or update the data before rendering the data on view or UI. Filters are clubbed in expression or directives using pipe (|) symbol.

What is the correct way to apply multiple filters in AngularJS?

Answer: A is the correct option. The syntax of applying multiple filters in AngularJS can be written as: {{ expression | filter1 | filter2 | ... }}


1 Answers

The anyPropertyKey is related to the expression of the filter. The relevant part of the documentation is:

A special property name ($ by default) can be used (e.g. as in {$: "text"}) to accept a match against any property of the object or its nested object properties. That's equivalent to the simple substring match with a string as described above. The special property name can be overwritten, using the anyPropertyKey parameter.

So the first thing here is that this expression:

<div ng-repeat='x in ar | filter: "1": false'>{{x}}</div>

is equivalent to this expression:

<div ng-repeat='x in ar | filter: {$:1}: false'>{{x}}</div>

So instead of a simple substring match, an object is used with a special key ($ by default) to match any property of the object with the value 1.

The anyPropertyKey parameter can be used to overwrite the default $ property like this:

<div ng-repeat='x in ar | filter: {"@":1}: false: "@"'>{{x}}</div>

In this last example we use the @ symbol to match any property name, freeing up the $ for other purposes.

The following snippet shows the same output for all three expressions:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<body ng-app="">
<div ng-init="ar=[{n:'ram1', m:1}, {n:'mah', m:1}, {n:'vij', m:3}]">
  <div ng-repeat='x in ar | filter: "1": false'>{{x}}</div>
  <hr />
  <div ng-repeat='x in ar | filter: {$:1}: false'>{{x}}</div>
  <hr />      
  <div ng-repeat='x in ar | filter: {"@":1}: false: "@"'>{{x}}</div>
  <hr />
  </div>

</body>
like image 89
ebo Avatar answered Dec 04 '22 03:12

ebo