2

I'm writing a module, using a custom filter, and I noticed something weird. if I use console.log() inside a filter, it logs the value twice, even though I call it only once. Is there a way to log it only once? Does that mean the code inside the filter gets executed twice?

Here's the filter:

.filter('arrayToSentence', function($sce, $rootScope) {
    return function(array, index) {
        console.log(index);
        var i, word, sentence = '<span style="color:red;">';
        for (i = 0; i < array.length; i++) {
            if (i < array.length - 1) {
                sentence += array[i] + '&bnsp;';
            } else {
                sentence += array[i];
            }
        }
        sentence = sentence += '</span>'
        return $sce.sentence;
    }
})

The console.log(index) is logging twice. I need to make sure that my filter logic will not be duplicating anywhere, as further down I need to compare two arrays (the one being filtered, and another one to colour the differences between them, like missing word, or word mismatch).

[EDIT] It is pointed out to me that my question is a duplicate, of this Yet the original question doesn't answer how to avoid this issue, but I believe @defaultcheckbox provided a fulfilling answer.

5
  • 1
    Can you include an example where this happens? Commented Aug 30, 2016 at 14:35
  • where you calling this filter? Commented Aug 30, 2016 at 14:35
  • 1
    Possible duplicate of Is this normal for AngularJs filtering Commented Aug 30, 2016 at 14:37
  • <ul> <li ng-repeat="x in sentenceList"> {{ x.text | arrayToSentence:$index }}<br/> <md-button ng-click="viewSentence($index, 'correctSentence', currentUser)" ng-if="x.proper[0]!=null || currentUser=='Teacher'">Correct</md-button> </li> </ul> This is the part of the HTML that calls the filter. Commented Aug 30, 2016 at 14:46
  • @yeouuu I didn't find that duplicate, thank you for this. Commented Aug 30, 2016 at 14:48

1 Answer 1

5

Are you using the filter in the DOM with piping, or are you using it in the controller? Using a filter in the DOM will always be "slower" than using one in the controller, but more importantly (and possibly related to your case) DOM filters always run twice.

source: https://toddmotto.com/use-controller-filters-to-prevent-digest-performance-issues/

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I am using the filter in the DOM, I need to figure out how to put it into the controller, thank you for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.