Ayeye Brazo Ayeye Brazo - 1 year ago 57
AngularJS Question

Re run angular filter on scope change

The application I'm building has an option for Users to change the unit distances between kilometers and miles.

I've build a small filter to convert those distances:

app.filter('distance', function() {

return function(input, scope) {
var distanceName = (scope.units.distance === 'km') ? 'km' : 'ml';

// scope.units.value is 1000 by default and 0.621 if miles are selected.
return (input / scope.units.value).toFixed(2) + distanceName;


In my template I use it simply like that:

{{ point.distance | distance }}

The issue is when the
change the filter do not update the value, I should re run the filter in someway... Even if I expect it to be done by Angular, but it doesn't.

When the value change the digest is started so if I force it with
it fire an error.

How can I solve it, what I'm missing for it to work?

Answer Source

The second (and consequent) input arguments to a filter are specified using the colon : operators. Right now you're not specifying a second argument to your filter.

points.distance is the input argument, arguments specified after colons are the rest of the possible parameters.

So in your case units.distance maps to scope on your filter, which is a confusing name, consider changing it to measurement or something like that

For your filter to work you also need units.value. Add an additional parameter to your filter return function(input, measurement, value) ... and use it like so

{{ point.distance | distance:units.distance:units.value }}