String includes another String not refreshing automatically

How come myCtrl.greeting doesn't automatically update when I change myCtrl.name?

angular.module('MyApp', [])
    .controller('MainController', [function(){
        var mCtrl = this;
        mCtrl.name = '';
        mCtrl.greeting = 'Greetings ' + mCtrl.name;
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MainController as mCtrl">
    <input type="text" ng-model="mCtrl.name">
    <h3 ng-bind="mCtrl.greeting"></h3>
</div>
    

I assumed that updating the mCtrl.name property would trigger a $digest loop and update mCtrl.greeting in the view?

Answer №1

The reason for this issue is not related to angular, but it actually stems from JavaScript. When you assign the value of name to your greeting string, a copy of the value of name is made, not a reference. This means that even if the value of name changes, the value of greeting remains the same. Here's a simple example to explain:

var a = 'Foo';
var b = a + 'bar'; //b = 'Foobar', there is no reference to a
b == 'Foobar'; //This is true

a = 'Lalelu';
b != 'Lalelubar'; //b is still 'Foobar'

To achieve the desired behavior, create an expression in your template like this:

<h3>Greetings {{mCtrl.name}}</h3>

This approach works well. Give it a try below.

angular.module('MyApp', [])
    .controller('MainController', [function(){
        var mCtrl = this;
        mCtrl.name = '';
        mCtrl.greeting = 'Greetings ' + mCtrl.name;
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MainController as mCtrl">
    <input type="text" ng-model="mCtrl.name">
    <h3>Greetings {{mCtrl.name}}</h3>
</div>

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

Retrieve the image by its unique identifier while viewing a preview of the image before it is uploaded

Below is the script I am using to preview an image before it is uploaded. The HTML structure looks like this: <div> <img id="image" src="#"> </div> <input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(th ...

Secure Flask API used for serving JSON files to a basic HTML, JavaScript, and CSS web application

I have developed a basic web application that will display data in a table and be updated on a weekly basis. To perform this update, I utilize Python code in the backend to scrape and modify data before storing it in a SQLite database. After some researc ...

What steps can be taken to enhance the functionality of this?

Exploring ways to enhance the functionality of JavaScript using the underscore library. Any ideas on how to elevate this code from imperative to more functional programming? In the provided array, the first value in each pair represents a "bucket" and the ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...

Capture JavaScript results using PHP

I'm looking for a way to save the output or result of JavaScript code. For example: <script>document.write(navigator.appVersion)</script> When it comes to PHP, I have no issues: $ip = $_SERVER['REMOTE_ADDR']; $file = "log.txt ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Postponing the loading of a controller until the model is fully loaded without relying on routes

One way to delay the changing of routes until the model is fully loaded is by using a resolve object. To learn more, visit: Delay changing routes until model loaded Is there a similar approach that can be taken for controllers without involving routes? ...

The sequence for conducting operations within a function in JavaScript (Vue.js)

I am currently working on building a contact-list app using Vue.js. Each contact in the list can have multiple addresses, emails, and phone numbers. To accommodate this, I have set up inputs and a button to add additional fields as needed. My issue arises ...

Can an element on a webpage be dynamically assigned an ID using JavaScript or PHP?

Is it possible to dynamically set the ID of an element during runtime of a webpage? Let's consider this scenario - <body id="body1"> Now, I would like to dynamically set the ID of this "body" element using a variable value in PHP code. Is som ...

The issue with NGX-Bootstrap/Angular Pagination arises when attempting to adjust the maxSize input while the screen view (width) is being altered

Currently, I am utilizing the Pagination component from Valor Software (click here to access). I am interested in adjusting the maxSize input dynamically based on changes in screen width. For reference, please see this example: Click to view example. It ...

One of the great features of Next.js is its ability to easily change

At the moment, my dynamic path is configured to display events by their ID [id].js localhost:3000/event/1 But I would like it to be structured as follows: localhost:3000/city/date/title. All of this information is available in the events database, but I&a ...

Tips for converting file byte code to file form data

From one folder I am retrieving a file and uploading it to another server. However, when I extract the file from the first folder, I receive a byte code representation of that file. The API for uploading the file to the second folder requires FormData as a ...

After the page is reloaded, apply a class to the divs by selecting them based on the "data" attribute

I have a set of four cards labeled "card", each representing different body parts: eyes, torso, arms, and legs. <div class="card" data-lesson="eyes">eyes</div> <div class="card" data-lesson="torso">torso</div> <div class="card" ...

The installation of robotjs via npm failed due to issues encountered while trying to build the binaries

After attempting to execute the command "npm install robotjs -g," an error is thrown back at me. [email protected] install C:\Users\Ehsan\AppData\Roaming\npm\node_modules\robotjs prebuild-install || node-gyp reb ...

shifting the length of o to the right by zero with the

While exploring the polyfill function for Array.includes, I stumbled upon the following lines of code: // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 4. Let n be ? ToInteger(fromIndex). // (If fromIndex is undef ...

Get the page downloaded before displaying or animating the content

Is there a method to make a browser pause and wait for all the content of a page to finish downloading before displaying anything? My webpage has several CSS3 animations, but when it is first loaded, the animations appear choppy and distorted because the ...

Encountered a Puppeteer Protocol issue: Error occurred when attempting to call a function on a closed

Exploring the world of JavaScript and nodejs as a beginner. Attempting to create a PDF table with node.js through Google puppeteer. Referenced a tutorial for the code below, all credit goes to the original source. Using a sample HTML template to populat ...

Mastering the art of reading rows in ASP.NET using Java Script

Within the code snippet below, you'll find an image located in the second column. Clicking on this second column should allow me to access the data stored in the first column. Let's say we have a table with 10 rows. If the user clicks on the ico ...

Troubleshooting Transclusion Problems in Angular

Is there a way to reference an array using i instead of # when using transclude in a repeat function? In the code below, my list is generated correctly with the right number of items from the array, but only returns data for x rows as specified in the mark ...

Posting a string using AJAX to the Java backend through JavaScript

I'm currently working on a comment section for a Web Client. There are two tables involved - one for the comments and another for the users. My goal is to send input data from HTML <input> tags to a Java Service where the data will be processed ...