What is the reason for AngularJS not utilizing the most recently assigned value?

<html>
    <head>
        <title>Test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="angular.js"></script>
    </head>
    <body ng-app="">
        <p>There {{count = 1; (count == 1 ? "is" : "are")}} one of them</p>
        <div ng-init="count = 7; unit = 'days'; collection = 'week'">
            <p>
                There are {{count}} {{unit}} in a {{collection}}.
            </p>
        </div>
    </body>
</html>

Within this code snippet, the variable count is initially set to 1 and then reassigned to 7, but the displayed result is as follows:

There is one of them

There are 1 days in a week.

This unexpected behavior raises the question of why the global scope precedence rule is not being followed? Shouldn't the last assigned value be displayed instead?

Answer №1

Within the {{}} interpolation in AngularJS, the expressions are evaluated during each digest cycle to maintain synchronization with the corresponding models. The expression count = 1 is evaluated multiple times whenever a digest cycle is triggered, resulting in the observation of 7 values.

In conclusion, it is advisable not to use {{}} for variable assignments. It is recommended to declare variables inside the controller. Avoid using ng-init for initialization; it is better to initialize variables within the controller itself.

Answer №2

If you're not currently working on a scenario involving Angular value assignment but rather creating a component to display the appropriate message based on a value, consider using the ngPluralize directive.

You can easily refactor your component like this:

<ng-pluralize count="count"
              when="{'one': 'There is one {{unit}} in a {{collection}}',
                     'other': 'There are {} {{unit}}s in a {{collection}}'}">
</ng-pluralize>

Feel free to experiment with this plunk:

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

The current state of my DOM doesn't match the updated value in my model. The update is triggered by a function that is called when a button is clicked

app.controller('thumbnailController', function ($scope) { debugger $scope.customers = [ { name: 'Ave Jones', city: 'Phoenix' }, { name: 'Amie Riley', city: 'Phoenix&ap ...

Issue with Fancybox and Jquery compatibility

I'm encountering some issues with conflicting Javascripts. One script is responsible for creating a dropdown menu, while another set of scripts enable fancybox functionality. However, having both sets of scripts in the header code results in conflicts ...

Angular Persistent States in Angular version 2 and beyond

Currently, I am in the process of transitioning an Angular 1.5.X application to Angular 4. Within my app, I incorporate Angular Ui-Router Sticky State from https://github.com/ui-router/sticky-states to prevent loss of content within my view when navigating ...

Displaying a picture solely in a designated region

I created a basic menu using an unordered list: <ul class="courses"> <a href="#"> <li class="spinny"> <h3>Course Title</h3> <img class="rotateme" src="images/logo_transparent.png"/> </li& ...

Use include files to wrap content in a div tag

I have a webpage index.html with the following JavaScript scripts: <script type="text/javascript> $(document).ready(function() { $('a.link').click(function() {var url = $(this).attr('href'); $('#content'). ...

Is there a way to make a React Component to update and navigate to a specific position using react-sound

Currently, I am in the process of constructing an audio player utilizing react-sound. One feature I aim to incorporate is the ability to return to a specific position within the audio track. At the moment, this is my approach: goToVeryCustomPosition() { ...

The system encountered an error while attempting to access the property "getChild" of an unspecified object

I am currently developing a react application and encountering an issue when trying to call a function from the render method. The function I'm trying to call utilizes the getChild method, but I keep receiving an error stating "cannot read property &a ...

Struggling to customize checkbox design using HTML and CSS

Why am I unable to style HTML checkboxes with CSS? No matter what I try, the appearance of the checkboxes remains unchanged: Here is the HTML code: <input type="checkbox" id="checkbox-1-1" class="regular-checkbox" /> <nput type="checkbox" id ...

Centered iframe within a div

I am trying to center my iframe within a white box and need some assistance with this. I want the iframe to be in the middle of the white box rather than its current position at the moment. game1.html: <html> <head> <title>R ...

Struggling to devise a for loop for a JavaScript-generated list

I'm attempting to loop the content of an H1 element through a list 10 times. I seem to have made a mistake in my code and would appreciate any guidance. var headOne = document.createElement("H1"); headOne.textContent = "Hello World"; document.body. ...

Understanding how to handle errors in Javascript using promises and try/catch statements

Seeking assistance because I'm having trouble grasping a concept... Here's the code snippet: // AuthService.js login(user) { return Api.post('/login', user); }, // store/user.js async login(context, user) { try { let ...

Using ng-repeat with an AJAX-called JSON is not possible

I've been struggling with handling JSON data from an AJAX call and displaying it using ng-repeat. If you want to take a look at my code in a more organized way, I've shared it on http://jsfiddle.net/7quj9omw/. However, please note that the code ...

The error message "ECONNRESET" occurred while attempting to send a post request using Axios to

Attempting to send a post request to my webserver using axios, I have a client that collects user input to populate an array of strings. This data is then sent via a post request using axios for processing by the server: if (parsedInput > 0 &&am ...

Can transitions be applied to links in this manner?

Having an issue with ajax requests, I am currently resorting to using JavaScript linking. This is how I normally link: window.location.href = ('file:///android_asset/www/custom/kontakty.html'); I am curious if it's possible to add a transi ...

Identifying the differences between a select2 dropdown and select2 multiselect: a guide

I currently have two different controls on my page: a select2 dropdown and a jquery multi value select Select2 Dropdown <select id="drp_me" class="select2-offscreen"> <option value="1">one</option> <option value="2">two</op ...

Implementing the array name property in a JSON object using ES5

I am currently working with a JSON object that has the following structure: {"Firstname":"john","Lastname":"doe"} My goal is to transform it into an array with a specific name 'abc': users: [{"Firstna ...

Is there a way to print messages to the console of openDevTools in Electron JS?

After finishing a hello world application using electron js, I have successfully printed to my terminal with console.log and opened the openDevTools in the window of my application. However, I am now interested in finding a way for my console.log stateme ...

jQuery ajax doesn't function properly on the server, it only works locally

When I send a jQuery Ajax request from my front-end to the back-end to retrieve values for calculations, it works perfectly on my local web server. However, when I try it online, all I get is a result of 0 in my calculations, indicating that the Ajax respo ...

Performing simultaneous AJAX requests in Javascript and jQuery

function makeCall(file, handlerFile, sendMethod, formData) { //console.log(instance.files); $.ajax({ url: handlerFile, type: sendMethod, xhr: function() { // Custom XMLHttpRequest var xhr = $.ajaxSettings.xhr() ...

Using Google Apps Script to input data into the next available row

Utilizing Google Apps Script, I am retrieving data from another spreadsheet and storing it daily in a sheet named "DATABASE". Although my current solution is basic, it keeps overwriting existing data. I wish to enhance the script to copy data from the imp ...