Step-by-step guide on defining a property within the ng-repeat's scope

My goal is to create a dynamic list of items that can be edited individually. Each item should have its own editing mode.

Here's the code I'm using:

<ul ng-controller="ItemCtrl">
    <li ng-repeat="item in items">
        <div class="edit-off" ng-hide="item.editMode">...</div>
        <div class="edit-on" ng-show="item.editMode">...</div>

        <button ng-click="toggleEdit(item)">Edit</button>
    </li>
</ul>

And here's the JavaScript part:

angular.module("app", [])
    .controller("ItemCtrl", function($scope) {
        $scope.items = [...]; // list of items

        $scope.toggleEdit = function(item) {
            item.editMode = !item.editMode;
        };
    });

After reviewing this code, I realized that I mistakenly attached the editMode property to the controller scope instead of each individual item's scope. This caused all items to switch into editing mode simultaneously when any edit button was clicked.

I now understand that I need to assign an editMode property to each item's scope so that they can be edited independently.

Answer №1

Add a property to each item:

<ul ng-controller="ItemCtrl">
    <li ng-repeat="item in items">
        <div class="edit-off" ng-hide="item.editMode">...</div>
        <div class="edit-on" ng-show="item.editMode">...</div>

        <button ng-click="toggleEdit(item)">Edit</button>
    </li>
</ul>


angular.module("app", [])
    .controller("ItemCtrl", function($scope) {
        $scope.items = [...]; // list of items

        $scope.toggleEdit = function(item) {
            item.editMode = !item.editMode;
        };
    });

Answer №2

To implement the use of $index, follow this example:

angular.module("app", [])
    .controller("ItemCtrl", function($scope) {
        $scope.items = [...]; // list of items
        $scope.editMode = [];

        $scope.toggleEdit = function(index) {
            $scope.editMode[index] = !$scope.editMode[index];
        };
    });

HTML:

<ul ng-controller="ItemCtrl">
    <li ng-repeat="item in items">
        <div class="edit-off" ng-hide="editMode[$index]">...</div>
        <div class="edit-on" ng-show="editMode[$index]">...</div>

        <button ng-click="toggleEdit($index)">Edit</button>
    </li>
</ul>

Demo: https://jsfiddle.net/iRbouh/rftfx7j4/

Answer №3

If you want to customize each item, you can include a property for editing purposes.

 $scope.items = [{name: 'misko', gender: 'male'},{name: 'misko1', gender: 'male'}];

  angular.forEach($scope.items, function(obj) {
    obj["editMode"] = false
  });

When displaying the items in the view:

<ul ng-controller="ItemCtrl">
    <li ng-repeat="item in items">
        <div class="edit-off" ng-hide="editMode[$index]">...</div>
        <div class="edit-on" ng-show="editMode[$index]">...</div>

        <button ng-click="item.editMode = !item.editMode">Edit</button>
    </li>
</ul>

Answer №4

Utilize the $index variable.

Here is an example using HTML:

<ul ng-controller="ItemCtrl">
    <li ng-repeat="item in items track by $index">
        <div class="edit-off" ng-hide="editMode">...</div>
        <div class="edit-on" ng-show="editMode">...</div>

        <button ng-click="toggleEdit($index)">Edit</button>
    </li>
</ul>

And here is a snippet of JavaScript code:

angular.module("app", [])
    .controller("ItemCtrl", function($scope) {
        $scope.items = [...]; // list of items

        $scope.toggleEdit = function($index) {
            setEditMode($scope.items[$index]);
        };
    });

function setEditMode(item) {
    item.editMode = false;
}

Answer №5

To implement the editMode feature for each item, follow the instructions provided in @John's response. Check out the functional Plunker link below:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
   $scope.items = [
      { id:2, ds: 'test1' },
      { id:2, ds: 'test2' },
      { id:2, ds: 'test3'}]; // list of items


        $scope.toggleEdit = function($index) {
            $scope.items[$index].editMode = !$scope.items[$index].editMode;
        };
});

Answer №6

Here is one way to implement this using AngularJS:

<ul ng-controller="ItemCtrl">
<li ng-repeat="item in items">
    <div class="edit-off" ng-hide="editMode[$index]">{{editMode[$index]}}</div>
    <div class="edit-on" ng-show="editMode[$index]">{{editMode[$index]}}</div>

    <button ng-click="toggleEdit($index)">Edit</button>
</li>

var myApp = angular.module("myApp", [])
.controller("ItemCtrl", function($scope) {
    $scope.items = ["aaa","bbb","ccc"]; // list of items
    $scope.editMode = [true,true,true];

    $scope.toggleEdit = function(index) {
        $scope.editMode[index] = !$scope.editMode[index];
    };
});

Visit this link for a live demo.

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

It's time to wrap up the session with some old "cookies" and a closing function

Would like the message to only display once after clicking the "Cookies" button. Once the user accepts cookies, they should be stored on their device for a set period of time. Your assistance is greatly appreciated. :) Below is the html and js code: $(do ...

Patience is key as you await the element to load and smoothly render the data in vue.JS

Is there a way to ensure that the graph is only rendered and filled with data after the data has been returned from the backend? Currently, even though the data is returned, the graph appears blank. Here is my JavaScript code: methods: { refresh( ...

Using VueMultiselect with Vue 3: A guide for beginners

I'm currently experimenting with the vue multiselect component, but when I include it in the template, I am encountering a series of warnings and errors. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...

What is the solution for - Uncaught TypeError: Cannot access the property 'scrollHeight' of an undefined element?

Could someone kindly assist me in resolving an issue? I recently encountered a problem with a script I have been using on the Chrome console. This script has been working perfectly fine for the past few days. However, today when I ran it, I started receiv ...

Utilizing express.js to access an HTML document

var express = require("express"); var fs = require('fs'); var sys = require('sys'); var app = express(); app.use(express.logger()); app.get('/', function(req, res){ fs.readFile('/views/index.html'); }); ap ...

Encountering an error with an undefined callback argument within an asynchronous function

I encountered an issue while working with the viewCart function. I have implemented it in the base controller and am calling it from the home controller. However, I am facing an error where the callback argument in home.js is showing up as 'undefined& ...

I am encountering an issue where the nested loop in Angular TypeScript is failing to return

I am facing an issue with my nested loop inside a function. The problem is that it is only returning the default value of false, instead of the value calculated within the loop. Can someone please point out what I might be doing incorrectly? Provided belo ...

Tips for arranging Intervals in sequence?

I've been developing a customized Pomodoro timer with user-defined work and rest times. In my Timer component, I have the following initial logic: useEffect(() => { start(3); start(timeData.workTime); start(timeData.restTime); }, []) c ...

Socket.io continuously refreshing and updating multiple instances

Incorporating socket.io into a small React application, I configured all the listeners within the "componentWillMount" method. See the code snippet below for reference: componentWillMount() { const socket = io(); socket.on('update', f ...

Leverage AJAX for real-time Django Model updates

Seeking insights on how to effortlessly update a Django model through AJAX without reloading the page or requiring user input for saving. Various tutorials address fetching data from Django models using AJAX, yet resources on updating models remain scarce. ...

Embedding a label's text directly as HTML code in an ASP.NET page

I attempted this CABC</td><td valign="top"><span class="progressBar pb3">document.getElementById('<%#Label8.ClientID%>').innerHTML</span></td></tr> I am trying to incorporate a jQuery script for a sales ...

Stop the reloading of the parent page when the exit button is pressed on the popup screen

I have set up a modal popup that appears when a user clicks on a specific link. Inside the popup, I have included an exit button to close it. However, I am facing an issue where clicking on the exit button not only closes the popup but also reloads the par ...

During the rendering process, the property "instance" was attempted to be accessed but is not defined

I am having trouble creating a Contact Us page using v-model. My code keeps throwing these errors: Property "inputted_name" was accessed during render but is not defined on instance Property "inputted_email" was accessed during render but is not defined o ...

Trigger a fire event upon entering a page containing an anchor

My query is similar to this particular one, with slight differences. I am working on a page that includes an anchor, such as page.html#video1. Within this page, there are multiple sections identified by ids like #video1, #video2. Each section comprises of ...

Sorting two different divisions is an example

I need advice on how to toggle between two divs, A and B, without having to reload the page. Ideally, I would like to have three buttons - one that shows only div A when clicked, another that displays only div B, and a third button that shows both A and ...

The Field Projection operation is not taking into account the batchSize field name

I have a collection called user_batch which contains the following two documents: [{ _id: ObjectId("594baf96256597ec035df23c"), name: "Batch 1", batchSize: 30, users:[] }, { _id: ObjectId("594baf96256597ec035df234"), name: "Batch 2", batch ...

Tips for removing residue from old watches

Our angularJS web components are integrated with a jqxGrid. Whenever a user makes edits in a cell, we implement a custom typeahead editor using Angular. However, I have noticed that after the editor is destroyed, my $watches array does not revert back to i ...

Setting up a connection to MongoDB on a local network using express and mongoose

As I set up a server with express and mongoose, my goal is to make it accessible on other devices within my local network. To achieve this, I configured the bind_ip variable to 0.0.0.0 in the Mongodb configuration file. const connection = mongoose .co ...

What issues can be found in this code snippet for AngularJS in the browser code editor that is interacting with Node.js

Greetings, I am currently working on developing a free in-browser code editor for high school students at the basic level to share knowledge. After extensive research, I came across this link. Following the instructions provided, I made some setups and mod ...