0

In AngularJS, $filter provides a way to format the data we display to the user. However, $interpolate also allows us to live update a string of text.

Are $interpolate and $filter related to each other? How are these two conceptually different?

Aaditya Sharma
  • 3,330
  • 3
  • 24
  • 36

1 Answers1

1

You can think of $interpolate() as a specialized filter.

var interpolationFunction = $interpolate('{{thing}} is {{color}}.');

var grass = {thing: 'Grass', color: 'green'};
console.log(interpolationFunction(grass));

// Or just.
console.log(interpolationFunction({thing: 'Milk', color: 'white'}));
console.log(interpolationFunction({thing: 'The sky', color: 'blue'}));

That will produce:

Grass is green.
Milk is white.
The sky is blue.

You can think of the return value of $interpolate(STRING) as a compiled template that you later render with a set of variables.

By contrast, $filter(NAME) returns a function that was previously registered as a filter with the name NAME. For example the "uppercase" filter converts its arguments to uppercase, the "number" filter formats numbers, the "date" filter formats Date objects and you can define your own named filters that do arbitrary things with its arguments.

Guido Flohr
  • 1,871
  • 15
  • 28