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.
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/