Why is the view not reflecting the updates made to the model?

I recently started delving into Angular JS and have been following tutorials to learn it.

One issue I'm facing is that my model doesn't seem to update the view. Can anyone help me figure out why this is happening?

Here is the code snippet:

<!DOCTYPE html>

<div ng-controller="MyContr">
    {{xxx}}
</div>


<input type="text"  ng-model="xxx" ng-controller="MyContr" />
    <script>
    var app = angular
              .module("MyApp", [])
              .controller("MyContr", function ($scope) {
                  var xxx="Alexander"
                  $scope.xxx = xxx;
                 });
</script>

Answer №1

It appears from the code provided in the question that MyContr is being called twice,

The first instance is here:

<div ng-controller="MyContr">
    {{xxx}} <!-- xxx (instance 1) -->
</div>

and the second instance is here:

<!-- xxx (instance 2) --> 
<input type="text"  ng-model="xxx" ng-controller="MyContr" />

This means that two separate instances of the same controller are being created, resulting in each instance having its own unique xxx variable.

To resolve this issue:

Option 1 - Data sharing between instances can be achieved by referring to resources like Share data between AngularJS controllers and AngularJS: How can I pass variables between controllers?.

Option 2 - To address the problem, enclose both HTML elements within a single instance of MyContr as illustrated below:

<span ng-controller="MyContr">
    <div>
        {{xxx}}
    </div>
    <input type="text"  ng-model="xxx" />
</span>

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

After toggling the class, Jquery will no longer select the button

I am having an issue with my jQuery code where I have a button that, when clicked, should switch classes from #testButton to .first or .second. The image toggle shows that the first click works fine and toggles the image, but the second click does not seem ...

where is the yarn global registry located?

After updating yarn to point to my custom registry and verifying the changes, here is what I found: $yarn config list -g yarn config v1.22.10 info yarn config { 'version-tag-prefix': 'v', 'version-git-tag': true, ' ...

Can Google Charts columns be customized with different colors?

Is it possible to modify the colors of both columns in Google's material column chart? Here is the code I am using for options: var options = { chart: { title: 'Event Posting', subtitle: 'Kairos event p ...

I had hoped to remove just one item, but now the entire database is being erased

I present it in this way <tr v-for="(foodItem, index) in filteredFoodItems"> <td>{{ foodItem.name }}</td> <td>{{ foodItem.price | currency('£') }}</td> <td>{{ foodItem.category }}< ...

I am uncertain about how to interpret this method signature

Can you help me determine the correct method signature for handleError? The linter tslint is indicating an error message that says expected call-signature: 'handleError' to have a typedef (typedef). Here is the code snippet in question: import ...

The index.html file is failing to load/render when using app.js

I am currently in the process of creating a to-do list using an older tutorial. The app.js file seems to be functioning properly, however, when I try to run it locally, all I see is a blank page instead of my HTML content. Here is the code found in the ap ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

Convert XML data into a structured table format

We have an XML file named "servers.xml" that needs to be parsed. This file is located on the same server where we want it to be parsed, in the same folder. <root> <list> <server> <server name="28 Disconnects La ...

How can Javascript split main.js into two separate files using import or require?

Currently, my main.js file is functioning perfectly despite its length. However, I am interested in organizing my code by separating the functions related to 'y' into a separate file. In PHP, this process can be easily achieved with require(&apos ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

Issue: [$rootScope:inprog] AngularJS website encountered a problem

Upon loading my page, I intend to retrieve data from a database. The retrieval process is handled using Angular's http module as shown below: var fetchData = function(){ var params = { userId : 123, }; $http.post("url", params) ...

The content of XMLHttpRequest is accessible via the property response

Typically, when we want to retrieve data using AJAX, we would use code like this: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ elem.innerHTML = xhr.responseText; ...

Convert JSON objects within an array into HTML format

Is there a way to reformat an array of JSON objects that has the following structure? [{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}] The desired output in plain HTML text would be: 3 - Coca-Cola 3 - Rib Eye What is the best approach to ...

Fetching Data from Response Headers in Angular 4.3.3 HttpClient

(Text Editor: Visual Studio Code; TypeScript Version: 2.2.1) The main objective here is to fetch the headers of the response from a request Let's consider a scenario where we make a POST request using HttpClient within a service: import { Injec ...

What is causing the error "Next is not a function" to occur when exporting a Middleware function to the module.exports object?

In my logger.js module, I have a middleware function that I import into app.js and utilize. // ------ File : logger.js ------ // function log(req, res, next) { console.log('Logging details ... '); next(); } module.exports = log; // ---- ...

Encountered a problem when incorporating delay functions into redux-saga testing using the Redux Saga Test Plan library

I am facing a challenge while trying to test my redux-saga functions using the Redux Saga Test Plan library. The issue arises due to delay functions present in my saga. All tests pass smoothly without any errors when I remove the line containing yield del ...

Highlighted option selection in Material UI dropdown using Cypress

Can someone explain how to select Material-UI dropdown options using Cypress? I'm looking for a simple explanation, thanks! ...

Tips for incorporating 'and' in the 'on' clause of 'join' in knex.js

I need assistance implementing the following SQL code in knex.js: select c.id,c.parent_id,c.comment,u.username,c.postid from comments as c join post_details as p on (p.id = c.postid and c.postid=15)join users as u on (u.id = c.userid); I attempt ...

What is the best way to transfer the text from an input field into a paragraph when a button is

For a school project, I am developing a website focused on time management. My goal is to create an input text box that, when the "add task" button is clicked, transfers the text inside it to a paragraph or p2 element and then moves the input field down. ...

The output of the Node.js crypto.pbkdf2 function may not match the result obtained from CryptoJS.PBKDF

Currently, I am utilizing PBKDF2 on both the frontend with CryptoJS and the backend with Node.js. Despite using the identical salt, algorithm, number of iterations, and password, the derived keys are turning out to be different. Below is the code snippet ...