Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: greater than filter with ng-repeat

I'm applying a greater than filter to a ng-repeat tag. I wrote the following custom filter function:

$scope.priceRangeFilter = function (location) {
    return location.price >= $scope.minPrice;
};

and I use it in the following HTML code:

<div ng-repeat="m in map.markers | filter:priceRangeFilter">

What is the best way to trigger a refresh of the ng-repeat tag when $scope.minPrice is updated?

like image 279
Julien Avatar asked Jul 31 '13 14:07

Julien


People also ask

How do I filter in 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 does ng-repeat do?

Definition and Usage. The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

Where is the last element in NG-repeat?

You can use $last variable within ng-repeat directive. Take a look at doc. Where computeCssClass is function of controller which takes sole argument and returns 'last' or null .


2 Answers

It should be automatic. When $scope.minPrice is changed, the repeater will be automatically updated.

function Ctrl($scope,  $timeout) {
    $scope.map = [{
        name: 'map1',
        price: 1
    }, {
        name: 'map2',
        price: 2
    }, {
        name: 'map3',
        price: 3
    }];
    $scope.minPrice = 0;
    $scope.priceRangeFilter = function (location) {
        return location.price >= $scope.minPrice;
    };

    $timeout(function () {
        $scope.minPrice = 1.5;
    }, 2000);
}

Demo on jsFiddle

like image 116
zs2020 Avatar answered Oct 02 '22 04:10

zs2020


Create the filter as a filter service using the angularjs filter api, and add minPrice as a parameter.

filter('priceRangeFilter', function ( location ) {
    return function ( location, minPrice ) {
        ...
    }
})

and in the template

<div ng-repeat="m in map.markers | priceRangeFilter:minPrice">

See an example in this fiddle: http://jsfiddle.net/Zmetser/BNNSp/1/

like image 40
Oliver Avatar answered Oct 02 '22 04:10

Oliver