Double invocation of AngularJS custom filter

I have successfully created a custom filter using AngularJS that displays only the fruits that begin with the letter "p." Although I believe my custom filter is implemented correctly, I have noticed that it is being called twice.

While searching for similar issues on stackoverflow, I came across a person with a similar problem. However, their problem remained unanswered and was slightly different from mine.

Check out my JSFiddle Solution here

Here is the snippet of HTML code:

<body>
    <div ng-controller="ExampleCtrl" ng-app="sampleApp">
    <div class="showDiffTags" ng-repeat="val in values | myFilter:'p'">{{val.name}}</div>
    </div>
</body>

And here is the AngularJS code snippet:

angular.module('sampleApp', []).filter('myFilter', function() {

  return function(items, firstLetter) {
    var groups = [];
    console.log("called function");
    console.log(items.length);
    for (var i = 0; i < items.length; i++) {
      if (items[i].name.substring(0, 1) == firstLetter) {
    groups.push(items[i]);
      }
    }
    return groups;
  }
}).controller('ExampleCtrl', function($scope) {
  $scope.values = [{
    name: 'apple'
  }, {
    name: 'banana'
  }, {
    name: 'orange'
  }, {
    name: 'avocado'
  }, {
    name: 'pineapple'
  }, {
    name: 'peach'
  }, {
    name: 'plum'
  }, {
    name: 'grapes'
  }, {
    name: 'mango'
  }, {
    name: 'papaya'
  }, ];
});

Answer №1

It is correct behavior and is closely linked to the functioning of the $digest cycle.

Whenever the model changes, the $digest is executed at least twice:

  1. After the model changes, it runs the watchers and updates the models.
  2. It checks if the first $digest made changes to the model, and if so, another digest is called up to a maximum of ten iterations before Angular throws errors.

There is no need to worry unless you have many functions in templates and unstable models that change frequently.

I have updated your fiddle with a simple button that updates the model in the scope.

http://jsfiddle.net/U3pVM/22610/

<button ng-click="numModel = numModel + 1">
  update model {{numModel}}
</button>

You will notice that every time you click the button, the filter runs twice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attain worldwide reach

I'm currently facing a Scope issue that has been quite challenging to resolve. The saying goes, "a picture is worth a thousand words," and in this case, it couldn't be more true. Whenever the OK or REJ buttons trigger the reject() function, passi ...

Get the color at a specific index in a JavaScript array

When I click a button, a pie chart is generated using chartjs. The results are displayed based on the filters applied, showing (Name | Value%): Service_1 | 10 Service_2 | 15 Service_3 | 75 Sometimes, certain results may not appear: Service_1 | 20 S ...

ng-if behaving unexpectedly

This is a demonstration of how I populate the Table and attach checkboxes to a controller: <tr ng-repeat="key in queryResults.userPropNames"> <td><input type="checkbox" data-ng-checked="selectedKeys.indexOf(key) != -1 ...

Creating a sleek animated analog clock using CSS and jQuery

I am facing a small issue with my CSS3/jQuery analog clock. Currently, the movement of the clock hands is a bit abrupt. I would like the animation to be smooth. I attempted using transition: all .1s, but it gets messy when the clock hands reach the top po ...

Error: "the cart variable in the ctx object has not been defined"

A project I'm currently working on involves a pizza ordering app, and my current focus is on implementing the Cart feature. Each user has their own cart, which includes specific details outlined in cart.ts import { CartItem } from './cartitem&a ...

Understanding ng-app Directive in AngularJS

Kindly take a look at the code snippets I've included below. Scenario 1: Example of an AngularJS Application <div ng-app = ""> <input type="text" autofocus="autofocus" placeholder="Enter your name" ng-mode ...

Having trouble with my ajax request not functioning correctly

<body style="margin:0px; padding:0px;" > <form method="post" > <input type="text" id="city" name="city" placeholder="Enter city name"> <input type="submit" value="Search City" id="searchid"/> ...

Preventing audio from being muted using JavaScript requires the removal of audio tags through a MutationObserver

I attempted to utilize the script below to eliminate all audio from a specific website: // ==UserScript== // @name addicto // @namespace nms // @include http://* // @include https://* // @version 1 // @grant none // ==/UserScrip ...

Directly insert an image into your webpage by uploading it from the input field without the need to go through the server

Can an image be uploaded directly from <input type="file" /> into an HTML page, for example through the use of Javascript, without needing to first save the image to the server? I am aware that AJAX can accomplish this, but if there is a way to ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...

Using Angular to bind dynamically inserted HTML div elements

Apologies for the duplication, I have exhausted all similar questions but none provided a solution. I am in the process of integrating angular.js into an existing legacy system. The system currently utilizes the .load jquery function to dynamically load d ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

Angular JS Integration with PapaParse

Currently enjoying the efficiency of PapaParse's CSV parsing and unparsing features. Interested in integrating this with Angular JS - anyone able to assist with this integration? Excited about incorporating PapaParse into an Angular environment. Work ...

Error: The property 'classList' of null is unreachable for HTMLImageElement

I'm facing an issue on my website that's causing the following error message to pop up: Uncaught TypeError: Cannot read property 'classList' of null at HTMLImageElement. Here's the code I've been using: https://jsfiddle. ...

Refreshed page causing hide/show div to reset

Hello there, I'm currently working on a web application and I need to implement some JavaScript code. The application consists of three sections, each with its own title and button. When the button is clicked, a hidden div tag is displayed. Clicking t ...

Nested views within nested views in UI Router

Exploring the capabilities of angular-ui and specifically experimenting with the ui-router module to create nested views. I'm running into an issue where a partial isn't rendering within another partial: The structure of nesting looks like this: ...

After being initialized, the added Vue.js DOM elements do not function together

I updated an HTML page with ajax contents and incorporated Vue.js for front-end events. Unfortunately, the dynamically added elements are not interacting with the Vue.js instance, even when I attempted to forceUpdate them. Any suggestions on how to resol ...

Exploring the Differences between HTML Values in HTML and jQuery

Can someone assist me with comparing HTML values to check for equality? I am looking to compare the values of two select elements in HTML and needing guidance on how to accomplish this. Specifically, I want to determine if the selected values from both s ...

Refresh the data list displayed within a specified div container

On my jsp page, I initially populate a model attribute with some data. Then, I use the following code to display this list on the jsp page: <c:forEach var="pattern" items="${patterns}"> <li class="list-group-item liitem"><st ...

What is the process of extracting a value from an array of objects based on another parameter?

Given the array below which contains objects with nested arrays, my goal is to retrieve the value 'AUS Eastern Standard Time' when 'Australia/Melbourne' is passed to the array. Although I attempted to use the code var winTimeZone = arr ...