Issues with AngularJS edit functionality for records not functioning as expected

I have implemented a feature on my page where users can add objects to an array. These objects are then displayed on the page along with links for editing each item in the array.

Each added item is assigned a primary key, allowing users to edit it later even if its position in the array changes due to deletion or reordering.

The functionality for adding items is working correctly, but I am encountering issues with the edit behavior. Whenever I update the ng-model that the form controls are bound to, the form does not display the record intended for editing. I suspect this might be related to $scope handling, although I have already declared the model within the parent $scope to address this.

To access the Plunker example, click on the following link: http://plnkr.co/edit/yDlPpFunxFLHPiI0kCdj?p=preview

<form ng-controller="formCtrl" novalidate ng-submit="submit()">
  <input type="text" name="name" ng-model="student.name" placeholder="Name">
  <input type="number" name="age" ng-model="student.age" placeholder="Age">
  <input type="hidden" ng-value="pk">
  <input type="submit">
</form>

<h1>Students</h1>
<ul>
  <li ng-repeat="item in students"><a href="#" ng-click="editStudent(item.pk)">{{item.name}}</a> - {{item.age}}</li>
</ul>

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

myApp.controller("myCtrl", ['$scope',  function($scope ){

    $scope.student = {};
    $scope.pk = 1;
    $scope.index = 0;
    $scope.students = [];

    $scope.editStudent = function (id) {


        for (var i = 0; i < $scope.students.length; i++) {
            console.log("Comparing " + $scope.students[i].pk+ " & " + id);
            if ($scope.students[i].pk == id ) {
                console.log("Editing pk nr.: "+ id);
                $scope.student = {
                    name: $scope.students[i].name,
                    age: $scope.students[i].age
                };
                $scope.index = id;
            }
        }


    };


}]);



myApp.controller("formCtrl",  ['$scope',  function($scope) {

    $scope.submit = function () {

        if ($scope.index === 0) {
            $scope.students.push({
                name: $scope.student.name,
                age: $scope.student.age,
                pk: $scope.pk
            });

            $scope.pk++;
            $scope.student = {};
        } else {
            for (var i = 0; i < $scope.students.length; i++) {
                if ($scope.students[i].pk == $scope.index) {
                    $scope.students[i] = {
                        name: $scope.student.name,
                        age: $scope.student.age,
                        pk: $scope.index
                    };
                }
            }

            $scope.index = 0;
        }
    };


}]);

Thank you for your help!

Answer №1

Check out the edits I made to your plunkr by clicking here.

Summary of changes:

  • Condensed to one controller instead of two for efficiency.
  • Utilized the $index property within ng-repeat for easier item editing.

Here is your updated HTML code:

<div ng-app="myApp" ng-controller="myCtrl as ct">

    <form novalidate>
      <input type="text" name="name" ng-model="newStudent.name" placeholder="name">
      <input type="number" name="age" ng-model="newStudent.age" placeholder="age">
      <input type="hidden" ng-value="pk">
      <input type="button" value="submit" ng-click="submit()">
    </form>

    <h1>students</h1>
    <ul>
      <li ng-repeat="item in students"><a href="#" ng-click="editStudent($index)">{{item.name}}</a> - {{item.age}}</li>
    </ul>
  </div>

And here is your revised JavaScript file:

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

myApp.controller("myCtrl", ['$scope',  function($scope ){

    $scope.newStudent = {};
    $scope.students = [];

    $scope.index = -1;

    $scope.editStudent = function (index) {
      console.log('Editing student: ' + $scope.students[index].name);
      $scope.index = index;
      $scope.newStudent = angular.copy($scope.students[index]);
    };  

    $scope.submit = function () {
      if ($scope.index < 0) {
        $scope.students.push($scope.newStudent);
      } else {
        $scope.students[$scope.index] = $scope.newStudent;
      }

      $scope.newStudent = {
        name: '',
        age: ''
      }

      $scope.index = -1;
    };

}]);

Note: I have updated the edit functionality to use angular.copy, ensuring changes are only applied upon hitting submit to avoid immediate updates.

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

The Flask CORS issue arises from the absence of the Access-Control-Allow-Origin header when using the redirect() function

I am currently working on setting up OAuth Twitter User-sign in using Flask API and Angular. Every time I click the sign in with Twitter button and a pop-up window opens, I encounter the following error message: XMLHttpRequest cannot load https://api.twi ...

Contrasting the purpose of a function in pure JavaScript versus a function within the scope of an Angular controller

Could someone clarify the distinction between declaring these two functions in an angular controller? function demo() { }; scope.demo = function() { }; Are these two functions similar in perf ...

Error: Undefined Function [Thinkster.io's Angular Tutorial Chapter 4]

Currently working on the Angular Tutorial provided by Thinkster.io and enjoying every bit of it. However, I've hit a roadblock in Chapter 4 that seems impossible to overcome. Whenever I attempt to execute a Post or Delete action, I encounter the follo ...

Installing Vue JavaScript using the npm command

Embarking on my journey as a Vue JS learner, I took the plunge to install Vue and delve into creating web applications using it. So, I globally added npm Vue. npm install --global vue-cli This action resulted in: npm WARN deprecated [email protected]: T ...

Adjusting Iframe Dimensions Dynamically with Javascript based on Anchor Location

I am experienced with handling this issue in flash, but I am struggling to figure out how to do it using Javascript and CSS. The problem involves an iframe that does not have an overflow property, and I need to modify its width/height. Is there a simple ...

Trouble with $sce in Angular.js causing limitations on passing desired content into my directive

I've successfully developed a directive that animates a PNG Sequence. Everything functions perfectly when I manually input the image url, but when attempting to pass a dynamic url, I encounter an error related to $sce disallowing it. Below is the cod ...

What is the best way to stop a current action when a new action is initiated?

My current setup involves an action creator that performs a costly calculation and triggers an action when the user inputs data in real-time. The challenge arises when multiple inputs are entered, as I want to avoid running the entire expensive calculati ...

Exploring Angular2: The Router Event NavigationCancel occurring prior to the resolution of the Route Guard

My application has routes protected by an AuthGuard that implements CanActivate. This guard first checks if the user is logged in and then verifies if certain configuration variables are set before allowing access to the route. If the user is authenticated ...

A guide to efficiently reusing parameter definitions in functions using JSDoc

Currently, I have HTTP handlers set up in my express application. I want to use JSDoc annotations to document these handlers in a reusable manner. Here is what I currently have: /** * * @param {functions.Request} req * @param {functions.Response} res ...

Issue: (SystemJS) XHR error (404) encountered in Angular2 Plnkrsandbox

The issue: https://i.sstatic.net/jUKBU.png https://plnkr.co/edit/910M73kwYKc8xPlSIU57?p=preview index <!DOCTYPE html> <html> <head> <base href="/"> <title>Angular 2.1.2 + TypeScript Starter Kit</title> <met ...

I'm having trouble figuring out the code for the path in the POST request for my basic login form application

I have built a basic login form application in node.js. Although I can successfully display the login form and input login data, my POST request to capture the login data is not functioning correctly. I am encountering a POST http://localhost:3000/client 4 ...

Alter the button's color seamlessly while staying on the same page

I have implemented a feature that allows me to change the category of photos without having to leave the page and it works perfectly. My next goal is to create a button system where the pre-defined category of a photo is indicated by a button with a green ...

Ways to access the content of the chosen <td> element using Vue?

I have a dynamic table where I retrieve data using $.ajax() from a database. The content in the rows is editable, and I need to save the changes made with vue.js. After updating the content, an $.ajax() function with 4 parameters (name, client_id, url, and ...

New jQuery div elements do not have animations when using $(document).on

After creating an animation function that worked well with hovering over squares and leaving a trail, I later needed to add or remove squares based on the page size. Seeking help from here, I discovered my bind animation function wouldn't work on new ...

Continuing the chunked file upload process using blueimp jQuery-File-Upload will allow for all uploads to be completed simultaneously

I am currently working on integrating file upload functionality using blueImp jQuery-File-Upload with angularJS. The file upload feature must support chunked uploads and should automatically resume the process if a chunk upload fails. Although uploading ...

AngularJS scope variable not getting initialized inside promise

I've encountered an issue with my code while using CartoDB. The goal is to execute a query using their JS library and retrieve some data. The problem arises when I attempt to assign the result as a scope variable in AngularJS, after successfully worki ...

Understanding the distinction between deleting and nullifying in JavaScript

var obj = {type: "beetle", price : "xxx", popular: "yes" ,.... }; If I want to remove all the properties from obj, what is the correct way to do it? Should I use delete obj.type; delete obj.price; delete obj.popular ... and so on. Or should I set ob ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

React app is having issues with Hammer.js when used together with touch emulator on touch devices

I've been experimenting with testing touch events using Hammerjs in React, and I'm facing quite inconsistent behavior across different browsers and events. Consider this basic code snippet: import React from 'react'; import PropTypes ...

I am eager to showcase a Pokémon image sourced from the API, but I am faced with the challenge of only having the image URL and not knowing how to display it effectively

As a beginner in programming, I am seeking some assistance. I have been able to retrieve a random Pokémon from an API and gather its data, including the ID, name, and picture. My main focus now is to display the image of the Pokémon in the custom modal I ...