The operation was computed twice

Below is an example:

test.html

<!DOCTYPE html>
<html ng-app ng-controller="AppController">
    <head>
        <script type="text/javascript"  src="angular.js"></script>
        <script type="text/javascript"  src="script1.js"></script>
    </head>
    <body>
        <div ng-include="'test1.html'"></div>
        {{testFn()}}
    </body>
</html>

test1.html

<div>{{testFn()}}</div>

script1.js

function AppController($scope) {
    $scope.testFn = function() {
        console.log("TestFn");
        return "test";
    }
}

It seems that the testFn function is executing four times instead of the expected two logs in the console. Even after removing

<div ng-include="'test1.html'"></div>

, there are still two logs showing up. What am I doing wrong?

UPDATED:

angular.js

// added console.log to original code
var ngBindDirective = ngDirective(function(scope, element, attr) {
  console.log("ngDirective", attr.ngBind);
  element.addClass('ng-binding').data('$binding', attr.ngBind);
  scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
    console.log("ngDirective - scope.$watch", value);
    element.text(value == undefined ? '' : value);
  });
});

test.html

<!DOCTYPE html>
<html ng-app ng-controller="AppController">
    <head>
        <script type="text/javascript"  src="angular.js"></script>
        <script type="text/javascript"  src="script1.js"></script>
    </head>
    <body>
        <div ng-bind="testFn()"></span>

    </body>
</ html>

console

createInjector - modulesToLoad undefined angular.js:2666
loadModules undefined angular.js:2756
createInjector - modulesToLoad 
["ng", Array[2]]
 angular.js:2666
...
<output truncated for brevity>
...
---------------------------------------------
ngDirective testFn() angular.js:12363
TestFn script1.js:3
ngDirective - scope.$watch test angular.js:12366
TestFn script1.js:3

Answer №1

UPDATE:

Angular undergoes a double interpolation process when running the digest cycle, ensuring that each expression is normalized before being rendered. This behavior has been confirmed in both this Github issue and this Stack Overflow post.

As a result, it is important for scope methods used in view expressions to be idempotent, consistently producing the same output with the same input.

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

Cross Domain Requests in Internet Explorer: Preflight not being sent

I have come across several similar discussions but none of the solutions provided have worked for me so far. Issue: In our current setup, we have three servers hosting our http-apis - two for testing and one for production. Lately, we have been deployin ...

Ways to achieve combined outcomes using ng-repeat

Check out this plunker. <div ng-repeat="subCategory in subCategorys | filter:{tags:tag}:true | orderBy:'id'"> {{subCategory.id}} {{subCategory.name}} {{subCategory.tags}} <br/><br/> The detailed information of ...

What are the best practices for managing data input effectively?

I am facing a challenge with input validation. I need to restrict the input to only accept strings of numbers ([0-9]) for the entity input field. If anything else is entered, I want to prevent it from overwriting the value and displaying incorrect input. I ...

Guide to converting an arraylist of custom objects into JSON using JavaScript

I have a List returned to the jag. It is of type (java.util.List) and I need to print it as a json. var storeForum = Packages.org.wso2.carbon.forum.registry.RegistryForumManager; var forum = new storeForum(); var start = request.getParameter(&a ...

Numerous occurrences of Autodesk Forge Viewer

I am facing a challenge in implementing multiple instances of the Autodesk Forge Viewer (v6.2) on my webpage, each hidden within tabs. The goal is to show and hide the viewer with a loaded model as the user switches between tabs. Although I have managed ...

Restrict the input to only allow for parentheses, disallowing any letters or numerical characters

Only parentheses are allowed in the input field; letters and numbers will not be accepted. function checkBrackets() { var inputVal = document.getElementById("input").value; var result = document.getElementById("strong").value; console.log(inputVal, ...

Leverage the source code of Angular 2 in your project for seamless integration

Currently in the process of setting up Angular with npm: npm install @angular... Encountering an issue where the TypeScript source files are not included. I would like to have access to debug the code using the TypeScript source files (with source maps). ...

Examining the execution of a function/method when a click event occurs within a functional component

It took me a while to realize that testing functional components with vue-test-utils can present some challenges In my case, I am utilizing Bootstrap-Vue's B-Button with a @click event that calls a function/method. When I attempt to test whether the ...

Experiencing an Internal Server Error while attempting to upload a product using AngularJS in the MEAN Stack

I'm currently struggling with an Internal Server error while trying to add a product through the http service ($http.post) in AngularJS. To provide you with the necessary details for assistance, here are the key files involved: **index.js : This file ...

I'm having trouble with using setInterval() or the increment operator (i+=) while drawing on a canvas in Javascript. Can anyone help me out? I'm new

I am looking to create an animation where a square's stroke is drawn starting from the clicked position on a canvas. Currently, I am facing an issue where the values of variables p & q are not updating as expected when drawing the square at the click ...

Sending a div class as a parameter to a JavaScript function

Wondering if it's possible to pass a div's class into a JavaScript function. I'm using SquareSpace so adding an id to the div is not an option, but it works fine with divs that have ids. JQuery is already loaded. This is my current train of ...

Failed to install angular-cli globally on the system

When attempting to globally install angular-cli, I encountered some errors. What steps should I take? C:\Users\Jahidul>npm install -g angular-cli npm WARN registry Using stale data from http://registry.npmjs.org/ because the host is inaccess ...

Creating a separation between Mongoose data access code and pure data objects in Node.JS using Object-Oriented Programming

I've stumbled upon a design dilemma regarding Mongoose - could it be that my approach is off? In the traditional OOP fashion, I aim to create a User class. This class includes various attributes such as username, firstname, lastname, salt, and hash, ...

Is it possible to use ng-src to point to a file stored locally?

I am currently experimenting with using ng-src to load images from a local folder, but I keep encountering 404 errors. Can ng-src actually reference a local folder, or do you always have to use a hardcoded path like http://example.com/imgs/{{work.img}}.jpg ...

creating folding effect using javascript and css with divs

I've been searching high and low on the internet for a solution like this, but so far I haven't had any luck. It seems like there might be a JavaScript script out there that dynamically changes the css -webkit-transform: rotateY(deg) property. ...

Switching templates in AngularJS

We have a unique challenge from our client who wants a responsive website, but desires to make significant content changes that may push the limits of bootstrap. Although bootstrap allows for showing/hiding blocks and adjusting their positions with offset ...

Determining when a message has been ignored using php

One of the features I am working on for my app is adding announcements, which are essentially personalized messages to users. Once a user receives a message and dismisses it, I want to ensure that specific message does not appear again. Here is the PHP co ...

standalone visuals generated interactively with matplotlib

While I appreciate the plots generated by matplotlib and the ability to save them as SVG, there is a feature missing that I would like to see added... I am looking for a way to save the figure as an SVG file with embedded JavaScript code to add interactiv ...

"Encountering a problem with using setState in React Hook useEffect

I am currently utilizing the useState hook with two arrays: imageList and videoList. In my useEffect hook, I iterate through the data using forEach method. If the type of the item is an image, it should be pushed to the imageList array. However, after exec ...

Is it possible to scroll down a page using Javascript/jQuery?

Is there a way to implement a "page down" action using Javascript/jQuery that functions correctly even if the user has adjusted their zoom settings? In other words, I need it to scroll exactly as much as it would if the user physically pressed the key for ...