Binding Events to Elements within an AngularJS-powered User Interface using a LoopIterator

I am working with an Array of Objects in AngularJS that includes:

  • EmployeeComments
  • ManagerComments
  • ParticipantsComments.
[{
  "id": "1",
  "title": "Question1",
  "ManagerComment": "This was a Job Wel Done",
  "EmployeeComment": "Wow I am Surprised",
  "ParticipantArray": [{
      "id": "1",
      "comment": "Oh i Dont think So"
    }, {
      "id": "2",
      "comment": "Oh i believe the same"
    }

  ]
}, {
  "id": "2",
  "title": "Question 2",
  "ManagerComment": "This was a Job Wel Done 1",
  "EmployeeComment": "Wow I am Surprised 1",
  "ParticipantArray": [{
      "id": "1",
      "comment": "Oh i Dont think So 1"
    }

  ]
}];

My goal is to display a textarea for each comment from the objects, along with Save/Edit buttons to allow users to edit, update, or add new comments.

I am currently exploring ways to achieve this and would appreciate any suggestions on how to approach this at an individual textarea level rather than affecting all textarea fields simultaneously.

Answer №1

Check out this plnkr link for a demonstration of how to achieve this.

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

app.controller('MainCtrl', function($scope) {
    $scope.tableData = [{
    "id": "1",
    "title": "Question1",
    "ManagerComment": "This was a Job Well Done",
    "EmployeeComment": "Wow, I am Surprised",
    "ParticipantArray": [{
        "id": "1",
        "comment": "I don't think so"
      }, {
        "id": "2",
        "comment": "I believe the same"
      }

    ]
  }, {
    "id": "2",
    "title": "Question 2",
    "ManagerComment": "This was a Job Well Done 1",
    "EmployeeComment": "Wow, I am Surprised 1",
    "ParticipantArray": [{
        "id": "1",
        "comment": "I don't think so 1"
      }

    ]
  }];

  $scope.tableDataCopy = angular.copy( $scope.tableData );

  $scope.save = function() {
    $scope.tableData = angular.copy( $scope.tableDataCopy );
  }

});

The controller manages your data and its copy to avoid direct manipulation of the model (hence the need for a save function).

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3e31382a333e2d71352c1f6e716b7127">[email protected]</a>" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
      <div ng-repeat="data in tableDataCopy">
        Manager comment:
        <textarea ng-disabled="!edit" ng-model="data.ManagerComment"></textarea>

        <br>
        Employee comment:
        <textarea ng-disabled="!edit" ng-model="data.EmployeeComment"></textarea>
          <div ng-repeat="participant in data.ParticipantArray">
            Participant {{participant.id}}: <textarea ng-disabled="!edit" ng-model="participant.comment"></textarea>

          </div>
        <button ng-click="save()">Save</button><button ng-click="edit = !edit">Edit</button>
        <br>
        <br>
        <br>
      </div>

      {{tableData}}
      <br>
      <br>
      {{tableDataCopy}}
  </body>

</html>

This serves as a basic demonstration of repeaters, data binding, and click events.

You can adjust the logic based on your specific requirements using this example as a guide.

Edit: Updated plnkr with individual controls

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e0818e87958c8192ce8a93a0d1ced4ce98">[email protected]</a>" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
      <div ng-repeat="data in tableDataCopy track by $index">
        Manager comment:
        <textarea ng-disabled="!editManager" ng-model="data.ManagerComment"></textarea>
        <button ng-click="tableData[$index].ManagerComment = data.ManagerComment">Save</button><button ng-click="editManager = !editManager">Edit</button>
        <br>
        Employee comment:
        <textarea ng-disabled="!editEmployee" ng-model="data.EmployeeComment"></textarea>
        <button ng-click="tableData[$index].EmployeeComment = data.EmployeeComment">Save</button><button ng-click="editEmployee = !editEmployee">Edit</button>

        <div ng-repeat="participant in data.ParticipantArray">
          Participant {{participant.id}}: <textarea ng-disabled="!participant.edit" ng-model="participant.comment"></textarea>
          <button ng-click="tableData[$parent.$index].ParticipantArray[$index].comment = participant.comment">Save</button><button ng-click="participant.edit = !participant.edit">Edit</button>
        </div>
        <br>
        <br>
        <br>
      </div>

      {{tableData}}
      <br>
      <br>
      {{tableDataCopy}}
  </body>

</html>

Answer №2

To cycle through your object, utilize ng-repeat. Assign each comment to a model within a text area. By doing so, any edits or updates made to the comment will automatically be reflected in your object thanks to Angular's two-way binding functionality.

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

A guide to tracing a button click with a personalized <img> tag in Google Tag Manager

Recently, a marketing firm provided me with a custom tag to implement on a Wordpress site for tracking clicks on specific buttons. I am utilizing the Elementor page builder and have assigned unique IDs to each button. Although I am new to Google Tag Manage ...

Upload files via Ajax request is required

I am in the process of trying to upload a binary file to a server while avoiding a full page refresh when the server responds. I must admit, I am not well-versed in this area and I understand if my approach needs some adjustments. This is how I have appro ...

Managing Input Type Dropdown Selections Using Jquery

I am currently in the process of developing a website. On this website, there is a form that includes 3 dropdown menus as shown below. I would like to implement a feature where selecting the number 5 from the Adults menu will automatically display 5 in the ...

Tips for improving the scrolling function in Java with Selenium for optimal performance

I'm currently working on a project using Java in MAVEN. My task involves retrieving a URL, scrolling down the page, and extracting all the links to other items on that website. So far, I have been able to achieve this dynamically using Selenium, but ...

What is causing my component callback to not function properly?

I'm currently following a tutorial on AngularJS callbacks from . In my code at https://plnkr.co/edit/dxyI0p0pZFZdMalLfvXO?p=preview, I've attempted to showcase the issue I'm encountering. I have initialized the component in three different w ...

Retrieve tabs according to the value selected in the dropdown menu

When a value is selected from a dropdown with options 1 to 5, I want to display a corresponding number of tabs. Below is the HTML code for the select box: <select id="Week" name="Week"> <option value="1">1</option> <option val ...

Arranging information extracted from an XML document following an ajax request

Here is a snippet of XML data sample to work with: <?xml version="1.0" encoding="ISO-8859-1"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>U ...

Guide on displaying multiple views along with their respective models fetched through AJAX in Backbone

Hey there! I'm currently working on painting a screen with multiple models and associated views in backbone. To achieve this, I have separate ajax calls to fetch data for these views. Initially, I thought using the jQuery function $when(ajaxcall1, aja ...

Troubleshooting problem with MongoDB queries within a for loop

I have an array of user emails obtained from the post data. My goal is to find the _id associated with each email. Here's the for loop I attempted: var studentIds = []; for (var i = studentEmails.length - 1; i >= 0; i--) { var email = studentEm ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

What is the most effective way to retrieve the children and ID of an item in the jQuery Nestable plugin following a drag-and-drop action,

I'm currently implementing the jQuery Nestable plugin to build a menu editor for a website. After users click on menu items and rearrange their positions, I need to retrieve the item's ID and its Children.   Challenge: I'm struggling with ...

Is it possible to time a page without relying on the Form tag?

As I search for solutions, I have come across some examples that require a Form tag, but unfortunately, it doesn't seem to integrate well with my current application. My goal is to implement a timer on a webpage that starts counting when one button i ...

Error: Unable to iterate over the elements of `this.state` as it is

NEW UPDATE I encountered an issue with the response being an array, but it was actually coming from the backend (Express/Build folder) Revisiting an old issue that I faced some time ago. In my development environment, everything works fine. But once I d ...

Having an issue in Angular 2 where the correct function is not triggered when a button is placed within a selectable anchor

Within an anchor element, I have a button that triggers its own click listener for an editing popup module. The anchor itself has another click listener assigned to it. For example: <a (click)="onClick(myId)" class="list-group-item clearfix"> < ...

What is the procedure for eliminating a cookie with Javascript?

Is there a way to delete the cookie set by javascript:void(document.cookie=”PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;path=/; domain=.google.com”); The code below fails to do so. javascript:void(docum ...

Creating asynchronous JavaScript constructors using a static method called "create" presents challenges when dealing with TypeScript types

I've been diving into the world of asynchronous constructors and have successfully implemented them in JavaScript. However, I'm facing a challenge with TypeScript types. Here's how it should ideally work: const a: AnyClass = await AnyClass. ...

Using a PHP switch case statement with an HTML multiple select dropdown

I am facing an issue with my HTML multiple select box: <option value="1">First choice</option> <option value="2">Second choice</option> <option value="3">Third choice</option> Using jQuery, ...

one-time occurrence of $mdToast injection within a parent class

Seeking advice on how to efficiently place a single instance of $mdToast (from Angular Material) into a base class (Typescript). In my UI, I have five tabs with separate controller instances and it seemed logical to centralize the $mdToast declaration in a ...

Looking to retrieve HTML elements based on their inner text with queryselectors?

I am looking to extract all the HTML divs that contain specific HTML elements with innerText = ' * ' and save them in an array using Typescript. If I come across a span element with the innerText= ' * ', I want to add the parent div to ...

What is the best way to randomly display an image from a JavaScript array within an HTML document?

I currently have this code in my HTML and JavaScript files, but I am having trouble with displaying images without using a URL in the JavaScript file. The images are located in my project folder. However, when I open the HTML file, the images do not appear ...