What is the reason behind having all bindings resolved during each $digest cycle?

Upon placing a breakpoint on a bound function, I discovered that it is being triggered every cycle. This came as a surprise to me as the timer displaying a countdown on the page was updating other properties as well.

The demonstration below showcases three instances of two controllers. Strangely, the first two dates get updated each time the $timer is executed, even though the second date belongs to a different scope.

To prevent the date from being constantly updated, I added a double colon (::) before the binding in the third date section. However, this solution does not scale effectively. How can I ensure only the timer element updates without affecting other bindings?

View Demo

http://plnkr.co/edit/1IhAabzBXMVl9LEfaf8M?p=preview

JavaScript Code

var app = angular.module('myApp', [])
  .controller('MainCtrl', ['$timeout', function($timeout) {
    var vm = this;
    vm.countDownLeft = 99999;
    vm.myFunction = function() { return new Date(); }

    function countdown() {
     vm.countDownLeft--;
     $timeout(countdown, 1000);
    }
    countdown();
}]).controller('SecondCtrl', function() {
  var vm = this;
  vm.myFunction = function() { return new Date(); }
});

HTML Markup

<div ng-controller="MainCtrl as vm">
  <p>Counter: {{vm.countDownLeft}}</p>
  <p>Updates: {{ vm.myFunction() }}</p>
</div>
<div ng-controller="SecondCtrl as vm2">
  <p>Updates: {{ vm2.myFunction() }}</p>
</div>
<div ng-controller="SecondCtrl as vm3">
  <p>Doesn't update: {{ ::vm3.myFunction() }}</p>
</div>

Answer №1

Currently, I am using jQuery to update the timer outside of Angular's $digest cycle as a temporary solution. It's not ideal, but it gets the job done;

Check out this Demo

http://plnkr.co/edit/cjNUKpRhP10OxYIfbnFj?p=preview

Here is the HTML code snippet

<div ng-controller="MainCtrl as vm">
  <p>Counter: <span id="countDownLeft"></span></p>
  <p>Updates: {{ vm.myFunction() }}</p>
</div>

And the JavaScript code snippet for the countdown function

function countdown() {
    vm.countDownLeft--;
    $("#countDownLeft").text(vm.countDownLeft);
    setTimeout(countdown, 1000);
}

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

Accessing the 'window' object within an Angular expression is not permitted unless using a controller

I am attempting to display a <p> only in the context of the HTTP protocol. This is my current progress: angular .module('myApp',[]) .controller('myCtrl', ['$scope', '$window', function($scope, $window){ ...

Increasing and decreasing the display of content using JQuery based on height rather than character count

I'm attempting to create a show more/show less link with a set height of 200px that, when clicked, will reveal the rest of the content. Anything exceeding 200px will be hidden, and there will be a "show more" link to display the remaining text. I&apos ...

Switch between Fixed and Relative positions as you scroll

Just a small adjustment is needed to get it working... I need to toggle between fixed and relative positioning. JSFiddle Link $(window).on('scroll', function() { ($(window).scrollTop() > 50) ? ($('.me').addClass('fix ...

Facing a problem with querying interfaces and types in TypeScript

My goal is to pass a variable to an RTK Query API service that uses a typescript interface: const device_id: unique symbol = Symbol(props.id); const { data: device, isFetching, isLoading, } = useGetAssetsByIdQuery(device_id, { pollingInterv ...

Problem with the "md-open-on-focus" behavior in the Angular-Material's "md-datepicker" directive

When testing the functionality of the fiddle, an inconsistency issue was observed with multiple openings of the md-datepicker while using md-open-on-focus. The problem arises after the first successful opening and closing - subsequent attempts to open it ...

What is the best way to ensure email address validation is done perfectly every time?

Can someone assist me with validating email addresses correctly? I am able to handle empty fields, but now I need a way to identify and display an error message for invalid email addresses. How can I modify my validation process to check for improper email ...

What is the reason behind the failure of the cancel test?

I've created two test cases; one for testing the functionality of the Download button and the other for the Cancel button. However, I am encountering issues with the Cancel test failing consistently. Below is the code snippet where I'm attemptin ...

Guide: How to include a date value within a JSON format? [See code snippet below]

Currently, I am developing a react application that includes a form with sections for basic details and employment information. The form is almost completed, and I have successfully structured the data in JSON format for different sections. To see a work ...

No data, response or issue received from the Internet API

In my web api project, I have created the following controller: public IEnumerable<Speciality> GetAllSpecialities() { List<Speciality> specialities = null; try { specialities = (new Datatable(Proper ...

Is there a way to insert an attribute in HTML without simply appending it to the end of the tag?

I've been working on incorporating the code snippet below that I found in an angularjs table sort function. In the code, you can see the ts attributes being added to the html. However, this method is not suitable for hosting on Salesforce. Can anyone ...

Understanding AngularJS binding: Decoding the mystery of "<?" symbol

After spending more than 10 minutes trying to find the answer, I'm certain that others will benefit from this information as well. Can someone explain the meaning of '<?' in AngularJS databinding when used for a directive? ...

Is it possible to achieve a file upload in splinter using Python?

A challenging task lies ahead with my web application, where users can upload XML-style files and make modifications directly in the browser. To test this scenario using Splinter, I need to ensure correct input (id="form-widgets-body"): Finding it is eas ...

How come setting an optionsValue causes Knockout updating to malfunction?

As I delved into the Knockout tutorials, one particular tutorial caught my attention. Here is the HTML snippet that puzzled me: <h2>Your seat reservations</h2> <table> <thead><tr> <th>Passenger name</th& ...

Converting JSON DateTime objects to local time in JQuery without considering timezones

I am struggling with parsing a JSON DateTime object using moment.js. Despite trying various methods recommended on Stackoverflow, nothing seems to work in my case. In my application, I save DateTime values in UTC format and when displaying them, I need to ...

The 'mat-table' component is triggering an error indicating that the 'dataSource' attribute is unrecognized in the table

Recently, I have been diving into the world of Material Library for Angular. Working with Angular version 15.0.1 and Material version 15.0.1, I decided to include a mat-table in my form (schedule.allocator.component.html): https://i.stack.imgur.com/c7bsO. ...

"Need to refresh localStorage in VueJS after navigating back with this.$router.go(-1)? Here's how

Below is my Login.vue code: mounted() { if (localStorage.login) this.$router.go(-1); }, methods: { axios.post(ApiUrl + "/login") { ... } then(response => { ... localStorage.login = true; this.$router.go(0); ...

Tips for organizing an object according to specific attributes

Within my table, I have implemented a feature that allows the display of only selected columns at a time. To achieve this, I store the chosen columns (table headings) in an array called selectedTableHeaders. The next step is to filter out a new array bas ...

Disable page scrolling after making changes to the DOM

When my JavaScript function executes on page load and at set intervals, it cycles through images supplied by another PHP script. However, every time the function manipulates the DOM, the page scrolls back to the top of the containing div, which is quite fr ...

Unable to fetch the number of items for ng-repeat pagination

I am currently working on setting up pagination within my ng-repeat template. I came across a code snippet on How to do paging in AngularJS?, which led me to this jsfiddle example: http://jsfiddle.net/dalcib/J3fjc/. My implementation closely resembles the ...

Changing Marker Color in Google Maps API

There are multiple Google Maps Markers colors based on certain conditions being TRUE or not. In addition, these Markers will change color when the mouse hovers over a division (a1,a2..ax). I want the Markers to revert back to their original color when th ...