raphael_turtle
raphael_turtle

Reputation: 7314

Access previous element item in angularjs filter

When creating a filter in angularjs how do I access the previous item in the array? i.e I want to compare the current element to the previous one

Upvotes: 0

Views: 378

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

Hard to figure out exactly what you're trying to achieve, but I think if you're using an ng-repeat you can do this:

HTML:

<div data-ng-repeat="element in elements">
    <div>{{ element | myFilter:elements:$index</div>
</div>

Javascript

.filter("myFilter", function(){
    return function(input, elements, index){

        if(index > 0){
            var previousElement = elements[index - 1]
        }

        return input;
    }
});

Edit

Ok now that you've specified what you're trying to do, you can use a filter in a different way to instead remove the duplicate dates.

Here's the filter:

.filter("uniqueDates", function(){
    return function(input){
      var returnInput = [];
        for(var x = 0; x < input.length; x++){
            if(returnInput.indexOf(input[x]) === -1){
                returnInput.push(input[x]);
            }
        }

      return returnInput;  
    };
})

Here's a jsfiddle with the html and everything all wired up that you can extrapolate from: http://jsfiddle.net/nE9EE/

Upvotes: 1

Related Questions