Changing elements within Angular Scope while in ng-repeat loop

Creating an HTML form using ng-repeat to generate form elements from an object in the scope is a common practice. However, issues may arise when trying to update values outside of the ng-repeat block.

Here's a basic example:

<div ng-app="App">
  <div ng-controller="Ctrl">
      <div class="block1">
          <form ng-repeat="(key, value) in test">
              <label>{{key}}</label>
              <input ng-model="value" />
              <p>{{value}}</p>
          </form>
      </div>
      <div class="block2">
        <p>
          {{test.a}}
        </p>
        <p>
            {{test.b}}
        </p>
      </div>
  </div>
</div>

It seems that while the <p> tags inside the ng-repeat block update correctly when modifying input values, the <p> tags in block2 do not reflect these changes.

This leads to questions about the behavior of ng-repeat and whether it creates its own isolated scope. Understanding this could help in finding a solution to ensure that the controller level scope updates properly. Additionally, analyzing the logic behind this behavior and exploring potential advantages it offers would be beneficial.

To investigate further, refer to this JSFiddle that demonstrates the issue.

Answer №1

ng-repeat creates a new scope for each item being repeated. When passing primitives to these child scopes, no reference is created back to the parent. However, when passing objects, the original object reference is maintained.

Words of wisdom from one of the Angular pioneers:

Always include a dot in ng-model

This insightful video on Angular Best Practices was presented by the creator himself on December 11th, 2012. Skip to minute 31 for a detailed explanation of this particular scenario.

Convert data to an array of objects:

$scope.test = [{ val:"abc",key:'a'}, {val:"def",key:'b'} ]

Then in the repeater:

<form ng-repeat="item in test">
  <label>{{item.key}}</label>
  <input ng-model="item.val" />
  <p>{{item.val}}</p>
</form>

See DEMO here

Answer №2

Check out this code snippet:

    angular.module('App', []);

function Ctrl($scope) {
    $scope.test = [
        {label:"a", value:"abc"},
        {label:"b", value:"def"}
    ]
}

Also, take a look at the following HTML markup:

<div ng-app="App">
  <div ng-controller="Ctrl">
      <div class="block1">
          <form ng-repeat="o in test">
              <label>{{o.label}}</label>
              <input ng-model="o.value" />
              <p>{{o.value}}</p>
          </form>
      </div>
      <div class="block2">
        <p>
          {{test[0].value}}
        </p>
        <p>
            {{test[1].value}}
        </p>
      </div>
  </div>
</div>

In AngularJS, objects are passed by reference. This means that if you pass an object to a function and modify it inside the function, the changes will reflect outside as well. For a practical example, you can refer to this updated JSFiddle link.

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

Separating unique values in an array of objects and storing the rest of the values in a separate

I have an array of JavaScript objects that I need to merge into a single JavaScript object based on their same property value. The remaining values should be grouped into another array named info. Original array: const array = [ { price: 27, ...

A guide on updating data dynamically in Vue.js

I am facing an issue with Vue JS in my frontend development. Here is the data for my component - data: () => ({ email: "", showError : false }), Below is the corresponding HTML code - <div v-show='showError' c ...

Issues encountered with the performance of a Laravel Vue.js application

I am encountering a recurring issue when trying to run new applications that combine Laravel with Vue.js. This problem persists whether I am working on a partially developed app or starting from scratch with a fresh Laravel installation. Upon setting up La ...

Struggling to find a solution to adjust an Angular directive

I am attempting to create a functionality where, upon clicking a button, the user can select one of two images displayed and make the selected image draggable. Currently, my code displays two images with only one being draggable. I am struggling to impleme ...

superagent is not providing any response within the specified time frame

My attempt to send a request with a query string is not producing any log in the console. I'm expecting some result back but both res and err turn out to be empty. superagent .get('http://localhost:4000/v1/process/web') .que ...

Implement a JavaScript and jQuery code that alternates between fading in and fading out every two items in a

Can someone help me figure out how to create a loop that fades in and out every 2 items from an unordered list using jQuery? I've been trying to do this, but my loop only processes one item at a time. <div> <ul> <li>item1</li ...

Difficulty with Vue Router horizontal scrolling to hash functionality

My goal is to achieve horizontal scrolling of the viewport by using a button wrapped in a router-link that navigates to a vue component. I was successful in achieving this functionality using anchor tags: <a href="#about"> <button cl ...

Tips for verifying that jQuery is functioning correctly and that the Jquery.min.js file has been properly loaded

My code usually functions correctly, but occasionally when I input data into the database, it returns output as JSON. Most of the time, the response contains "success" in JSON format, but sometimes I receive the complete JSON output. I have two main pages ...

Refresh the functional component when props are updated

I'm experiencing an issue where I am unable to display updated props in a functional component. Strangely, I can perfectly console.log these props without any problem. Here is a snippet of my code: class ABC extends someOtherClass { static create(v ...

Is there a way to dynamically adjust the carousel slide indicators based on the changing viewport size?

My carousel is inspired by the one at the following link: I am looking to make a modification where, as the screen size decreases, the bottom links disappear and are replaced with dot indicators for switching between slides. ...

Error: Attempting to access the 'SearchBox' property of an undefined variable is not allowed

I have been working on a Google Maps code that displays both public and private schools with different markers for each category. However, when running the code, I encountered an error specifically on this line of code: var searchBox = new google.maps.pl ...

MUI-Datatable: Is there a way to show the total sum of all the values in a column at once

I have a column displaying the Total Amount, and I am looking for a way to show this totalAmount. After conducting some research, it seems like onTableChange is the key. Currently, it effectively displays all of the data using console.log("handleTab ...

Is it possible to show an image without altering the Box dimensions?

Hi there, I am currently working on designing a footer and I have encountered an issue. I want to add an image in a specific position, but when I do so, it affects the size of the box. I was wondering if there is a way to set the image as a background or b ...

How to implement mouse hover functionality in C# using Selenium?

When attempting to mouse hover on a menu with multiple sub-menus, I encountered an issue where the suggested actions caused other menus to overlap and hide the intended element. Below is the recommended code snippet for hovering over the desired element: ...

What is the best way to assign various classes to individual elements depending on their content?

HTML <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-401 dt-mega-menu mega-auto-width mega-column-3"> <a href='#' data-level='1'> <i class="logo-png dnld-logo"></i> ...

Using default value in PHP and JavaScript for a select dropdown

I have an array of cities stored in associative arrays using PHP. I am utilizing JavaScript's "on change" event to capture the value of each item. In the future, I am considering implementing geolocation for setting a default item. Here are my arrays ...

Issue with page scrolling while utilizing the Wow.js jQuery plugin

While using the Wow.js plugin for scroll animations, I encountered an issue on mobile phones. When reaching the Pricings section, scrolling becomes impossible for some reason. I am utilizing Bootstrap 3 in this project. Despite attempting to modify the an ...

What is the correct syntax for utilizing a variable in inline styles within ReactJS, specifically when working with the --i:0

            The question has been raised previously, but unfortunately, it was left unanswered in this thread. The variables play a crucial role in this piece of code as they are intended to be utilized in various CSS functions for animating them wi ...

Ensure that only the most recent Ajax request is allowed

In my project, I have an input box that triggers an ajax request with every key press. This means if I type the word "name," there will be a total of 4 requests sent out. However, what I really need is to only execute the latest request. So even if I enter ...

JavaScript Fullcalendar script - converting the names of months and days

I recently integrated the Fullcalendar script into my website (https://fullcalendar.io/). Most of the features are functioning correctly, however, I am seeking to translate the English names of months and days of the week. Within the downloaded package, ...