updating specific values for each key in angularjs

Whenever I click on a particular value, I want to be able to edit only that specific value. However, the issue is that when I try to do so, it ends up editing all the values in that row instead of just the one I clicked on. Here is the code snippet:

<table>

<tbody ng-repeat="(key,value) in row.entity.subData"><tr ng-repeat="item in value" >
<td   >
  <span ng-hide="row.entity.editing(item)" ng-click="row.entity.editItem(item)">{{item}}</span>
<button ng-show="row.entity.editing(item)">save</button>
  </td>
</tr></tbody></table>

In my JavaScript code, I have the following function:

row.entity.editItem = function (item) {
    row.entity.editing=function (item) {
        return true; 
    }
}

The problem is that clicking on any value turns all values into buttons, not just the one that was clicked.

Answer №1

Looking at the code you provided, it seems like you have an object called row.entity.subData, which contains arrays of items.

It appears that your intention is to have a single click impact either a specific cell (item) or row (subData).

However, currently, when you click on a cell, the key "row.entity.editing" is changed to true. This causes all items in your ng-repeat to be affected by the click as there is only one reference to this variable.

To address this issue, you should modify a variable within each individual row.entity.subData[key], rather than applying changes to row.entity.* as a whole.

To resolve this problem, I suggest restructuring your data. You can nest objects inside an array with two values:

row.entity.subData = [{  isShown:true,  data: [...] }, ...]

The data key should contain the original values from your initial array.

The isShown key will determine the ng-if condition.

<table>
  <tbody ng-repeat="object in row.entity.subData">
  
    <!-- If you are hiding the entire row based on a click, the logic should be implemented at the row level -->
    <!-- Depending on the size of your dataset, using ng-if in a table is recommended -->
    
    <tr ng-if="object.isShown" 
        ng-click="object.isShown = !object.isShown" 
        ng-repeat="item in object.data" >
      <td >
        <span>
             {{item}}
        </span>
      <!-- Regarding the save button functionality, please clarify whether it should affect the cell or the row after clicking -->
          <button ng-show="object.isShown" ng-click="save(object)">
              save
          </button>
        </td>
    </tr>
  </tbody>
</table>

Answer №2

If you want to show or hide a specific item in an ng-repeat, I recommend structuring your data object like this:

angular.forEach(data, function(value){
     value.isVisible = false;
};

After that, you can easily show or hide the button for the item you wish to edit by toggling the value of isVisible as needed.

<table>
    <tbody><tr ng-repeat="item in data" >
    <td>
      <span ng-hide="!item.isVisible" ng-click="row.editItem(item)">{{item}}</span>
    <button ng-show="item.isVisible">save</button>
      </td>
    </tr></tbody></table>

I hope this explanation was useful. Best of luck with your project! :)

Answer №3

In my quest to find a solution for this issue, I came across the following code snippet:

function myCtrl($scope) {

  
   $scope.items = [{
        name: "item #1",
        id:4
        
    }
    ];

    $scope.editItem = function (value,$index) {
         if($index==0){
         $scope.editing =function ($index) {
       if($index==0){
       return true;
       }
        }
        $scope.backup = angular.copy(value);
         }
         if($index==1){
         $scope.editing =function ($index) {
       if($index==1){
       return true;
       }
        }
        $scope.backup = angular.copy(value);
         }
        
    }

    $scope.doneEditing = function (value,$index) {
    if($index==0){
         $scope.editing =function ($index) {
       if($index==0){
       return false;
       }
        }
        delete $scope.backup;
         }
         if($index==1){
         $scope.editing =function ($index) {
       if($index==1){
       return false;
       }
        }
        delete $scope.backup;
         }
       
    };
    $scope.Cancel = function (value,$index) {
     if($index==0){
         $scope.editing =function ($index) {
       if($index==0){
       return false;
       }
        }
        this.value = angular.copy($scope.backup);
        delete $scope.backup;
         }
         if($index==1){
         $scope.editing =function ($index) {
       if($index==1){
       return false;
       }
        }
         this.value = angular.copy($scope.backup);
        delete $scope.backup;         }
       
    };
  
}
.container {
    margin-top:10px;
    font-family:arial;
}
input:focus {
    //change more attributes, if you want.
}
input {
    border:none;
    background-color:transparent;
}
.container header {
    padding-bottom:20px;
    border-bottom:1px solid black;
}
ul, input, .container {
    padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<!DOCTYPE html>
<div ng-app ng-controller="myCtrl" class="container">
        <table>
        <tr ng-repeat="(key,value) in items[0]">
           <td>{{key}} </td>
           <td>
                <span  ng-hide="editing($index)"  > {{value}} <button  ng-click="editItem(value,$index)">Edit</button></span>
                <input ng-show="editing($index)" ng-model="value"  autofocus />
                <button ng-show="editing($index)" ng-click="doneEditing(value,$index)">Save</button>
                 <button ng-show="editing($index)" ng-click="Cancel(value,$index)">Cancel</button>
            </td>
        </tr>
         
        </table>
   
</div>

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

Implementing a Timer on an HTML Page with JavaScript

I am looking to add a timer to my HTML page using JavaScript. The timer should get the selected date and time from an input field <input type="date" /> and control it. If the time difference between the current time and the selected time is less than ...

"Discover the magic of jQuery: Unveiling the hidden div with one simple CSS visibility change

I want to implement a functionality on my screen where the Previous button is hidden initially and only becomes visible when the user clicks the Next button. I have set the CSS property for the Previous button to hide it by default, but despite using an if ...

Is integrating Vuetify with a project template created using vue-cli 3 causing issues when adding script tags to App.vue?

As a Vue beginner, I'm trying to wrap my head around a basic concept. In vue-cli 3, the "App.vue" file serves as the root component with <script> and <style> tags like any other component. However, after adding Vuetify to a project, the Ap ...

Exploring the internet with pattern validation in form input of type "number"

We recently encountered a strange bug in our web application that is specific to Internet Explorer. The input validation, demonstrated in this plunker, functions correctly on all browsers except IE (which we need to support from version 10 and above). Our ...

Is caching a feature in AngularJS, and are there methods available for disabling it?

var modalInstance = $modal.open({ templateUrl: '/template/edit-modal.html', controller: ModalInstanceCtrl2, resolve: { locations: function () { return locationToEdit; } }, scope: $scope.$new() }); ...

How come my reducer isn't changing the state of my store with ImmutableJS?

I have the following code within my reducer: const copy_states = fromJS(state); const i_copy_jobs = copy_states.get('calendar_jobs').get(s_from_day_key).get(s_dept_id).get(s_job_id); let i_calend ...

evaluating the elements of two arrays at corresponding indexes

I am dealing with two arrays that always have the same number of elements. The first array is $userInputArr=array("z","z","E","z","z","E","E","E","E","E"); and the second array is $user2InputArr=array("a","a","a","z","a","E","E","E","a","E");. My goal is ...

Unable to modify images and nicknames that have been selected from the steamapi

Having trouble syncing images and nicknames? Try using this: https://www.npmjs.com/package/steamapi New to promises and stuck at a point in your code? Here is the snippet of your code: const SteamAPI = require('steamapi'); const steam = n ...

Issue encountered with adaptor.fill operation

Below is the C# code snippet: using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics; public partial class _Upda ...

Troubleshooting: Issues with executing a PHP script from jQuery

I found the source code on this website: It's an amazing resource, but I'm facing an issue where my JavaScript doesn't seem to be executing the PHP script... When I set a breakpoint in Chrome's debugger before the penultimate line (}) ...

Is the on-error event not functioning properly in the <img> tag?

I am currently utilizing VueJS to develop the front-end of a project and encountered an issue with the image tag when loading images. Template <div class="items" transition="fade" v-for="item in list"> <img :src="item.logoPath" @error="replac ...

In VuePress 1.x, the functionality of using the <Content> tag with pageKey is not functioning as expected

Throughout the development process, we implemented a component that would iterate through each index.md file within a folder based on the list this.$site.pages.path. However, after upgrading to version 1.0.0-alpha.39 in order to address some other issues w ...

Preventing Vimeo from continuing to play when the modal is closed by clicking outside of it

I am facing an issue with my Vimeo video embedded in a modal. The video stops playing when I click on the 'close' button, but it continues to play in the background when I click off the modal. I have tried solutions from similar questions without ...

Obtain precise JSON information using Node.js

Having limited experience with Angular JS and Node JS, I find myself in need of assistance. On the server side, I have multiple JSON files containing language translations. Based on a client's request for a specific language, such as French, I must re ...

Filtering an array of objects based on another array of objects in Angular2 through the use of pipes

I'm having trouble understanding how to use the angular pipe to filter an array of objects based on another array of objects. Currently, I have a pipe that filters based on a single argument. I am working with two arrays, array1 and array2, both cont ...

Issue: Unauthorized access: nodeMailer despite correct configuration

Having trouble with an error when using the less app option on Gmail. I don't have 2-factor authentication enabled, and my credentials are correct. I can log in to my file to verify this, but the error still persists. const nodemailer = require(" ...

Freezing browser during an active AJAX call

I am currently working on an ASP.NET Web App and have noticed a peculiar issue. Whenever I make a simple ajax call (as shown below), the web application becomes unresponsive to any actions I try to perform on a different browser. $.ajax({ type: "G ...

Carrying over additions in arrays using only Javascript

I'd like to implement a basic array addition with carryover. Additionally, I need to display the carryover and result values. For instance: e.g var input = [[0,0,9],[0,9,9]]; var carryover = []; var result = []; Thank you! ...

Server-side form validation in Node.js with client-side feedback handling

Express-form is a validation plugin for node.js/express that offers powerful features. However, the examples and documentation currently only show server-side responses (console.log), which may not be very user-friendly. Two possible solutions come to min ...

"Refreshing UI-View with AngularJS and UI-Router: A Guide on Reloading Your

I am struggling with Angular UI-Router as I am encountering an issue where the state is not being reloaded. Here is a snippet of my code: app.config(function ($urlRouterProvider, $stateProvider) { $urlRouterProvider.otherwise("/home"); $stateProvi ...