The controller function is being executed two times due to the usage of ng-show

I have a basic Angular application set up with the following code:

index.html

<!DOCTYPE html>
<html>
  <head>
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js'></script>
    <script src='app.js'></script>
  </head>
  <body ng-app="app">
    <div ng-controller="MyCtrl">
      <div ng-show="ready()">
        Some content
      </div>
    </div>
  </body>
</html>

And app.js

var app = angular.module('app', []);

app.controller('MyCtrl', function($scope) {
  console.log("MyCtrl called")
  $scope.ready = function() {
    console.log("ready called");
    return true;
  }
})

When running this code with the console open, you will notice that "MyCtrl called" is logged once, and "ready called" is logged twice. This behavior has puzzled me as I expect $scope.ready to be called only once.

If you switch to Angular v1.1.5 and use ng-if instead of ng-show, the same issue occurs. However, when using ng-init, $scope.ready is correctly called only once. In my scenario, I require either ng-show or ng-if.

Plunkr: http://plnkr.co/edit/ZSwVNLeFSuhbouXZu9SM?p=preview

Clarification: To clarify my objective, if at some point $scope.ready returns false (e.g., after an AJAX call), "Some content" should no longer be visible. I aim to achieve dynamic behavior based on the result of $scope.ready.

Any thoughts or suggestions would be greatly appreciated. Thank you for your assistance!

For reference, this and this are not addressing the same issue.

Answer №1

This behavior is intentional, not a glitch (and it is unrelated to the AngularJS compiler, as stated incorrectly in another response). ng-show and ng-hide function by monitoring changes in the expression ready().

During each digest cycle, AngularJS assesses the linked expressions to detect any alterations. If a change is detected, the corresponding listener is triggered (in the case of ng-show/ng-hide, the element will be shown or hidden based on the output of ready()).

AngularJS does not settle for the initial value returned by

ready()</c ode>. This is because within the same digest cycle, other modifications could occur due to another expression, causing the result from <code>ready()
to change (such as the modification of an isReady variable that is part of ready()). Developers naturally expect the most recent value to be reflected in the DOM.

Therefore, AngularJS evaluates every watch expression at least once to ensure stability before concluding a digest cycle. While this can potentially result in infinite digestion iterations if an expression continues to change, AngularJS will generate an error if a digest cycle exceeds 10 iterations.

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

Popup appears on incorrect page

As part of my app development project, I implemented a popover feature that opens when clicking on a label. Initially, this functioned smoothly within a tab navigation setup. However, after transitioning from tab modules to the app-routing module to displa ...

Utilize Vue.js and express.js to distribute HTML files securely

Currently, my tech stack includes Vue.js for the frontend and Express.js for the backend. When I kick off the express.js server using npm start, my goal is to serve the Vue frontend component. By utilizing the Vue generator and Express generator, I attemp ...

Intermittent issue with Webdriver executeScript failing to detect dynamically created elements

It has taken me quite a while to come to terms with this, and I am still facing difficulties. My goal is to access dynamically generated elements on a web page using JavaScript injection through Selenium WebDriver. For instance: String hasclass = js.exec ...

The Javascript function is being called, yet it cannot be defined

I am currently in the process of revamping an older website that was originally designed for compatibility with IE8 and utilizes framesets for layout management. As part of this update, I am trying to implement a piece of code within one frame that will g ...

Automatically reduce the size of Java Script files and CSS files with compression

I'm currently working with Google App Engine and JQuery. I'm looking for a solution that can automatically compress my JavaScript and CSS files when deploying them to the GAE server. It's quite cumbersome to manually compress all the files e ...

Manipulate sibling elements using jQuery's addClass and remove methods

I have implemented a function that adds the class active to elements when they reach the top of the browser, ensuring that the next element will scroll in over the top. While this works smoothly in Chrome, I am encountering some jumping behavior when testi ...

Managing Dark Mode in Material UI with Redux

Having a React application integrated with Material UI, I encountered an issue with the dark mode functionality. Whenever I attempt to modify the dark mode state on a page where the content is rendered from redux state data, the entire page crashes. It app ...

What is the best way to send various types of parameters in a web API using AngularJS?

I am having difficulty passing parameters to my web API. There are two scenarios I will outline below. The first case involves passing a simple string parameter as shown below [HttpGet] public string VerifyName(string name) { ret ...

The Bootstrap 4 navigation bar fails to be responsive and remains open despite attempts at styling

Having trouble with my navbar functionality... After applying CSS styling, it loses responsiveness and remains open on smaller screens. Here is the code snippet. HTML: <nav class="navbar navbar-expand-sm navbar-dark bg-dark" id="big-bar"> ...

Arrange all absolute divs equidistant from each other

I'm struggling with positioning multiple absolute divs inside a relative container using the CSS 'left' property. I want these inner divs to be evenly spaced regardless of how many there are, without setting fixed values for each. Currently ...

What is the best method to generate a distinct identifier for individual input fields using either JavaScript or jQuery?

I have attempted to copy the table n number of times using a for loop. Unfortunately, the for loop seems to only work on the first iteration. I am aware that this is due to not having unique IDs assigned to each table. As a beginner, I am unsure how to cre ...

Displaying a webpage with a link using express.js

What is the process of rendering a page in express.js routes while including the anchor tag? For example: website.com/route#id-of-html-element ...

Unable to store a customized class object in Parse database

I have been attempting to create a Customer class object that is linked one-to-one with the User class. However, despite my efforts, the object does not save and no error message appears. Here is the code I am working with: Parse.Cloud.afterSave(Parse.Us ...

A comprehensive guide on integrating jQuery with jsdom using TypeScript

I am struggling to use jQuery with jsdom in typescript. This is the snippet of code I currently have: import { JSDOM } from 'jsdom'; import jQueryFactory from 'jquery'; const jsdom = new JSDOM(html); const { window } = jsdom ...

Is it possible for jQuery UI Autocomplete to utilize values from various input fields simultaneously?

I've hit a roadblock with this code and it's been giving me trouble for some time now. Here is the current state of my auto-complete script: jQ19(function(){ // minLength:1 - how many characters user enters in order to start search jQ19 ...

Instructions for loading custom field data from a WordPress post using ajax

Even though I am not proficient in PHP programming and unfamiliar with data fetching, I am attempting to create a template that dynamically loads custom field values of posts via AJAX in WordPress. The rationale behind using AJAX for loading these values ...

What is the process behind Stackoverflow's "Congratulations, you've earned a new badge" popup window?

Possible Duplicates: Custom notify box similar to StackOverflow Creating popup message like StackOverflow How does StackOverflow implement the "You earned a new badge" window? (the orange one that pops up at the top of the screen, I believe it&ap ...

When a single object is modified in a JavaScript array, all the elements are affected

I am working with an array of 71 objects: var data = [] This array is populated with data from a database, containing both static and dynamic elements for each object in the data. angular.forEach(returnData,function(value,index) { if(!Array.isArray(va ...

Error with NEXTJS: Prop type failed - The prop `href` in `<Link>` is expecting a `string` or `object`, but received `undefined`

After importing the Link from next/link and attempting to pass the dynamic endpoint in my components, I encountered an error message. https://i.stack.imgur.com/eqUK8.png https://i.stack.imgur.com/eIC4V.png I searched for a solution and came across a sug ...

What is the process for incorporating the JavaScript "star" feature from Google's search results page?

In the Google search results, each entry has a star that users can click to indicate if the result is good or not. This feature is likely implemented using JavaScript. I'm interested in implementing a similar function in my own web application. I wou ...