change the value of ng-model in ng-repeat using the controller

I'm working on creating a list of editable inputs based on a set of items. I want users to have the ability to edit any item, with an option to reset it back to its original state if they change their minds.

Everything is functioning well so far, except for the reset feature.

Here's my HTML:

<div ng-app ng-controller="TestController">
<div ng-repeat="item in list">
    <label>Input {{$index+1}}:</label>
    <input ng-model="item.value" type="text" ng-click="copy(item)"/>
    <button ng-click="reset(item)">
    x
    </button>
</div>
{{list}}<br>
{{selected_item_backup}}
</div>

This is my controller code:

function TestController($scope) {

$scope.selected_item_backup = {};

$scope.list = [ { value: 'value 1' }, { value: 'value 2' }, { value: 'value 3' } ];

$scope.reset = function (item) {
    // This code snippet is just a representation of what I aim to achieve as I understand that it may not work due to various reasons.
    item = $scope.selected_item_backup;
};

$scope.copy = function (item) {
    angular.copy(item, $scope.selected_item_backup);
};
}

You can also access the coded example through this fiddle: http://jsfiddle.net/ryanmc/1ab24o4t/1/

Please note that this simplified version does not reflect the complexity of my actual project. The objects will have multiple editable fields each, and they won't be indexed, making reliance on index numbers impossible. My main goal is to replace the new item with the original one by stacking them on top of each other.

Answer №1

Check out the solution on this jsfiddle link

function TestController($scope) {

  $scope.list = [{
    value: 'value 1'
  }, {
    value: 'value 2'
  }, {
    value: 'value 3'
  }];
  var orgiinalList = [];
  angular.forEach($scope.list, function(item) {
    orgiinalList.push(angular.copy(item));
  });

  $scope.reset = function(index) {
    $scope.list[index] = angular.copy(orgiinalList[index]);
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="TestController">
  <div ng-repeat="item in list">
    <label>Input {{$index+1}}:</label>
    <input ng-model="item.value" type="text" />
    <button ng-click="reset($index)">
      x
    </button>
  </div>
  {{list}}
  <br>
</div>

Answer №2

To modify your reset function for desired results, update it as shown below:

$scope.reset = function(index) {
    $scope.list[index].value = "value "+ (index+1); 
};

By making this adjustment, the 'reset' buttons will be able to restore the original values of each item in the list...

Angular controller logic:

function TestController($scope) {

  $scope.selected_item_backup = {};

  $scope.list = [{
    value: 'value 1'
  }, {
    value: 'value 2'
  }, {
    value: 'value 3'
  }];

  $scope.reset = function(index) {
    $scope.list[index].value = "value " + (index+1);
  };

  $scope.copy = function(item) {
    angular.copy(item, $scope.selected_item_backup);
  };
}

HTML structure:

<div ng-app ng-controller="TestController">
  <div ng-repeat="item in list">
    <label>Input {{$index+1}}:</label>
    <input ng-model="item.value" type="text" ng-click="copy(item)" />
    <button ng-click="reset($index)">
      x
    </button>
  </div>
</div>

The input fields represent the values of the array directly - any changes made by the user reflect on the $scope.list array, eliminating the possibility of using it as a reference... Hopefully, this explanation clarifies things.

Answer №3

In the latest versions of Angular, global functions cannot be used as controllers; however, you can still register your controllers within your application:

<div ng-app ng-controller="TestController">
    <div ng-repeat="item in list">
        <label>Input {{$index+1}}:</label>
        <input ng-model="item.value" type="text" ng-click="copy($index, item)"/>
        <button ng-click="reset($index, item)">
        x
        </button>
    </div>
    {{list}}<br>
    {{selected_item_backup}}

function TestController($scope) {
  $scope.selected_item_backup = [];   
  $scope.list = [ { value: 'value 1' }, { value: 'value 2' }, { value: 'value 3' } ];
  $scope.reset = function (index) {      
    $scope.list[index].value = $scope.selected_item_backup[index];
  };

  $scope.copy = function (index, item) {
    // backup the old value
    $scope.selected_item_backup[index] = item.value;
  };
}

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

unable to retrieve / interpret data from herdsmen using fetch

When sending a request to a node server, the server responds with headers and a blank body. Despite being able to view the headers in the network activity panel within dev-tools, I faced difficulties reading them using the following code: let uploaded ...

Retrieve a subset of fields from a collection of nested documents

My document looks like this: { "_id" : "2", "account" : "1234", "positions" : { "APPL" : { "quantity" : "13", "direction" : "long" }, "GOOG" : { "quantity" : "24", "direction" : "long" } } } I want to retrieve the entire positions object, but only ...

The Spotify Web API encountered an uncaught TypeError (in promise) stating that it cannot read the property 'setState' of an undefined object

I am facing an issue with Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined. I'm attempting to utilize this.setState to render some tracks, but I want to limit it to only 9 tracks to check if everything is done co ...

Have you ever wondered why the React HeroIcons architecture includes React.createElement instead of simply returning plain SVG elements?

As I integrate HeroIcons into my Next.Js app, I find myself pondering over how they have structured their package architecture. The way they return icons is like this: const React = require("react"); function ArchiveIcon(props, svgRef) { retur ...

The issue arises when attempting to access the response variable in a successful $http call within

Despite the fact that my backend is functioning properly and I'm receiving the correct response from Postman crafted request https://i.stack.imgur.com/JLIrQ.png I am unable to see the response in my angularJS controller. (I execute this call inside ...

Create a JSON array of objects and dynamically append new items to it

I'm feeling a bit lost and frustrated at the moment. I'm attempting to initialize a JSON Array and dynamically add JSON Objects to it during runtime, but something isn't clicking for me. Let's say I receive a list of repeated values fr ...

Error in React Typescript Order Form when recalculating on change

When creating an order form with React TypeScript, users can input the quantity, unit price, and select whether the item is taxable. In this simplified example, only 1 or 2 items can be added, but in the final version, users will be able to add 10-15 item ...

Delete a particular division within a row based on its unique identifier

I am currently working with Django and have integrated multiple Bootstrap cards into my page structure as shown below. I am attempting to delete a specific div element when clicking the 'X' button within an anchor tag. <row> <col-sm-3 ...

There was an error in locating the JavaScript file within the Node.js Express Handlebars application

My website is not displaying the .js file, css file, or image from the public folder. Here are the errors showing up in the console: GET http://localhost:8080/assets/images/burger.jpg 404 (Not Found) GET http://localhost:8080/burgers.js net::ERR_ABORTED ...

Using JavaScript to access the PHP web service that returns a JSON response

I am a beginner in PhoneGap and I'm looking to create my own android application using PhoneGap. I have attempted it multiple times but have not been successful. Does anyone have knowledge on how to "Access Web Service of PHP in JavaScript that will ...

The AJAX response containing jQuery is failing to produce any visible changes

On Page 1 of my website, there is a form that, upon submission, loads Page 2 using jQuery. This process involves calling a PHP page and displaying the output on Page 1 without actually reloading the entire page. To maintain security, I have set up session ...

Attempting to implement a disappearing effect upon submission with the use of JavaScript

I am currently working on implementing a disappearing form feature for a small web application. The idea is that once the initial form is submitted, it will be replaced by a new form. While my current code somewhat works, it only lasts for a brief moment b ...

Dealing with errors in cases where data is not successfully resolved using Angular UI router

Utilizing angular-ui-router's resolve feature to fetch data from the server before transitioning to a new state. I want to notify the user in case the request fails by triggering a Modal service, like a pop-up. I have a service that handles errors in ...

Vue3/Vuex - Issue with state change not being reflected in component when utilizing object destructuring

While working with Vue 3 and Vuex, I encountered an issue where Vue did not react to a state change when using object destructuring assignment to mutate the state. However, I found that Vue does react when the state is mutated by a mutation that only reass ...

Ember - connecting to a JSON data source

Recently, I have been following a tutorial/example from codeschool and everything is going well. However, the example code includes the line: App.ApplicationAdapter = DS.FixtureAdapter.extend(); Now, I want to maintain all the existing functionality but ...

Issue with unapplied nullable type during export操作

I'm struggling to understand why my nullable type isn't being applied properly Here's an illustration interface Book { name: string; author: string; reference: string; category: string; } async function handleFetch<T>(endpoin ...

Creating Dynamic Lists with React Native

<Search ref="search_box" onSearch={this.onSearch} backgroundColor="white" cancelButtonTextStyle={{ color: "red" }} placeholder="Search Food..." ...

Delete the child node that matches the specified variable

I am facing the challenge of removing a list item node if it matches a specific variable. For example If username is equal to User 1 And if a node is also User 1 Then I want to remove this particular node. Unfortunately, I have not been able to assign ID ...

How to iterate over an array and assign values to distinct labels using AngularJS

Challenge My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data. Each label is unique and w ...

Extract CSS from Chrome developer tools and convert it into a JavaScript object

Recently, we have started incorporating styles into our React components using the makeStyles hook from Material-UI. Instead of traditional CSS, we are now using JavaScript objects to define styles. An example of this is shown below: const useStyles = ma ...