The connection between ng-model and ng-repeat, and the comprehension of $scope

<!DOCTYPE html>
<html>
  <head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  </head>
  <body>
<div ng-app="myApp" ng-controller="customersCtrl">
  <ul>
   <!--Inside ng-repeat-->
<li ng-repeat="x in d">
   {{$index}} <input  ng-model="val">{{val}}
</li>
   <!--Inside ng-repeat--> 
<br><br><br>
   <!--Outside ng-repeat-->
Outer<input  ng-model="val">{{val}}
   <!--Outside ng-repeat-->
  </ul>
</div>
<script>
  var app = angular.module('myApp', []);
  app.controller('customersCtrl', function($scope) {

  $scope.d=[1,2,3,4,5];

  });
</script>
  </body>
</html>
Experiencing various scenarios with repeated AngularJS input fields I encountered several scenarios while analyzing the code snippet above. Scenario 1 highlights that all ng-repeated input fields share the same ng-model 'val'. However, any changes made to one input box do not reflect in all expressions. In Scenario 2, if the scopes of the repeated input fields are different, it raises questions on how to reference each scope individually, such as 'val[0]', 'val[1]', etc. While exploring Scenario 3, I observed that altering the value in the outer input field without affecting or modifying the ng-repeated input fields causes changes across all expressions. Conversely, changing a specific input field results in updates in all other inputs except for the one changed initially. This behavior raises queries about the scope and why it behaves this way.

Answer №1

One reason for this behavior is due to ng-repeat creating a child scope that inherits prototypically from the container scope. If you're unfamiliar with this concept, do some research online, as there are plenty of explanations available. Alternatively, you can refer to: https://github.com/angular/angular.js/wiki/Understanding-Scopes

To get a deeper understanding of what's happening, consider installing Angular Batarang in Chrome to inspect the scopes.

A cleaner approach to dealing with this issue is to use controllerAs like so:

<!DOCTYPE html>
        <html>
          <head>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
          </head>
          <body>
            <div ng-app="myApp" ng-controller="customersCtrl as vm">
              <ul>
               <!--Inside ng-repeat-->
                <li ng-repeat="x in vm.d">
                   {{$index}} <input  ng-model="vm.val">{{vm.val}}
                </li>
               <!--Inside ng-repeat--> 
                <br><br><br>
               <!--Outside ng-repeat-->
                Outer<input  ng-model="vm.val">{{vm.val}}
               <!--Outside ng-repeat-->
              </ul>
            </div>
            <script>
              var app = angular.module('myApp', []);
              app.controller('customersCtrl', function($scope) {

                  this.d=[1,2,3,4,5];

              });
            </script>
          </body>
        </html>

Detailed Explanation

Think of scopes in this simplistic way:

function ParentScope(){
    this.val = "parent";
}

function ChildScope(){

}

ChildScope.prototype = new ParentScope();
ChildScope.prototype.constructor = ChildScope;


var childScope = new ChildScope();

Explaining your scenarios:

1: Typing in an ng-repeated textbox causes ng-model to update the "val" property in the childScope, which actually exists in the prototype chain of the object.

childScope.val = "child"

This action creates a new property on the child object, hiding the parent property.

3: Typing in the text box outside ng-repeat changes the "val" in Parent Scope. Since child scopes inherit from the parent scope, they can access this property, causing all ng-repeated text boxes to display the same value. However, typing in an ng-repeated text box again tries to update the child scope, creating a new property and hiding the parent property once more.

I hope that clarifies things for you.

Answer №2

To achieve the desired outcome in scenario 2: In order to use different scope variables, you must follow the structure below:

<li ng-repeat="x in d">
    <input type="text" ng-model="val[$index]" ng-init="val[$index] = x">
</li>

For Scenarios 1 and 3: The input fields being repeated using ng-repeat will not be initialized initially until you assign a value to them.

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

Executing a click on a checkbox element in Python with Selenium

Background: Currently, I am in the process of developing a Python script that will automatically download listings from a specific website. I have successfully programmed the script to navigate the webpage, search for keywords, click on the search button, ...

What is the correct way to align text in jsPDF?

I'm currently encountering an issue with the jsPDF library. Although PDF generation works fine, I am struggling to justify text properly. The align: 'justify' attribute seems to function the same as align: 'left', and setting a spe ...

Issues with merging styles in TinyMCE 4

I've exhausted all the current configuration options and I'm still unable to resolve this issue. My goal is to have the style tag appended to the selected element without generating an additional span. For example: <p>Hello World!</p> ...

What is the best way to insert distinct values into an array in mongoDB?

I have a table of likes, and within that table, there is an array called videoLikes. I want to store the userData of users who have liked the video. However, when I attempt to add an object with a userId field to that array, I end up with duplicate data. S ...

Ways to take an item out of your shopping cart

Do you have any ideas on how to handle cart redirection in JavaScript? My specific request involves a cart with a function that removes products. What approach should I take to redirect to the main page if the cart becomes empty? Here is the delete produc ...

AngularJS ng-model not refreshing

One of the features in my application is a Font Awesome icon picker that allows employees to easily access different icons without having to search for their codes online. However, I am facing an issue where clicking on an icon does not update the ng-mode ...

Issue with modal component triggering unexpected page reload

I'm encountering a strange issue with my modal in Vue.js. It only appears on a specific page named 'Item', but when I click on a different view, the page reloads unexpectedly. This problem seems to occur only with the route containing the mo ...

`The compilation process in webpack doesn't seem to be picking up changes in files being

When I run webpack --watch and make changes to my JS files, it doesn't automatically recompile. I attempted to fix this by uninstalling webpack using npm uninstall, but the issue persists. Does anyone have any suggestions on how to resolve this? ...

"Easily toggle the visibility of values in checkboxes and organize them into groups with the power of JavaScript

Hey there! I am currently working on a project that involves grouping checkboxes and hiding/unhiding their content based on user interaction. Essentially, when the page first loads, the "All CARS" checkbox will be checked by default. If I then check the "C ...

What to do when faced with an NPM issue: Resolving the error "Unable to assign properties to null (setting 'parent')"

The issue arises in NPM when working within a monorepo that utilizes the NPM workspaces feature. Within my monorepo, I have five packages: a, b, c, d, and e. Additionally, I have a package located in a separate repository that is not part of the workspace, ...

Unable to invoke the jQuery function within CakePHP3

I am having trouble calling the jQuery function mentioned below in my CakePHP3 MVC project. There are no error messages, but nothing seems to be happening. The code is set up so that jQuery gets included automatically. The function I am trying to call sh ...

Switch Between More and Less Text - Implement Smooth Transition on Shopify Using Javascript

I recently implemented a More/Less toggle button using resources from this website. The functionality is there, but I now want to add a smooth transition effect. When the user clicks on "read more," I would like the hidden content to gradually appear, and ...

AngularJS $http response returns empty data and a status code of -1

Just delving into the world of Node.js and AngularJS. Employing MEAN stack for crafting a website that taps into predefined webservices. Issue arises when utilizing $http, as it consistently returns null data. Check out my code snippets: vendor.service.js ...

AngularJS not displaying loader during AJAX request

While utilizing ajax requests with $http, there seems to be a delay due to the server operation taking longer than expected. I have implemented a loader to display while processing the request, but unfortunately it is not showing up on the page. Even after ...

"Partially loaded" when document is ready

Is there a way for me to trigger a function once the element identified by #container has finished loading in the DOM? Instead of waiting for the entire DOM to load using document.ready(), I'd like to start populating #container right after it's ...

Revitalizing HTML and Google Maps with AJAX, PHP, and JQuery

Context: I am currently working on a project that involves integrating a Simple Google Map with an HTML form right below it. The form collects user input and upon submission, sends the data via AJAX to a PHP script for processing API calls and generating i ...

Failure of app script to retrieve data from an external spreadsheet

In an attempt to consolidate data, this program aims to transfer information from one spreadsheet to another. The process involves retrieving all files within a designated folder (all of which are spreadsheets), extracting values from a specific range, and ...

What are some ways to implement smooth scrolling when a navigation link is clicked?

I have a total of 3 links in my navigation bar and every time they are clicked, I want the page to smoothly scroll down to their designated section on the webpage. Although I have already set up the anchors, I lack experience in scripting to create the smo ...

constructing a nested container using XMLHttpRequest

I am working on creating a nested div-container structure using AJAX and adding the text "Hello World" to the inner container. The outer container serves as a holder for the inner container in this case. Below is the code I have written: index.html: ...

Learn the ins and outs of utilizing *ngIf in index.html within Angular 8

Can anyone explain how I can implement the *ngIf condition in index.html for Angular2+? I need to dynamically load tags based on a condition using the *ngIf directive, and I'm trying to retrieve the value from local storage. Below is my code snippet b ...