Attempting to reset the altered values proves ineffective in different Ctrl instances within AngularJS

I'm feeling a bit disoriented regarding my current issue. The scenario involves two views and a controller that interact with a service. The first view consists of a table list containing items loaded from a WebAPI. The service sends requests to the server and handles ordering. Additionally, another service is used to transfer the selected row item to the other controller. Below is the code snippet:

View 1:

//view1.html
<table class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>Firstname</th>
      <th>Lastname</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="item in namelist" ng-click="open(this.item)">
      <td>{{ item.fname }}</td>
      <td>{{ item.lname }}</td>
    </tr>
  </tbody>
</table>

Controller 1:

//FirstCtrl
$scope.namelist = reqService.names.query();

$scope.open = function (item) {
  $scope.selectedItem = item;           
  modalService.openDialog($scope.namelist, $scope.selectedItem);
}

HTTP Service:

//Service for HTTP Requests
testApp.factory('reqService', ['$resource', 'baseUrl', function ($resource, baseUrl) {
    return {
        names: $resource(baseUrl + '/api/name/:Id', {
            Id: '@Id'
        }, {
            'update': {
                method: 'PUT'
            }
        })
    }
}]);

Modal Dialog Service:

//Modal dialog service
testApp.factory('modalService', ['$modal', function ($modal) {
    return {
        openDialog: function (namelist, selectedItem) {
            return $modal.open({
                templateUrl: 'views/view2.html',
                controller: 'SecondCtrl',
                resolve: {
                    namedList: function () {
                        return namelist;
                    },
                    selected: function () {
                        return selectedItem;
                    }
                }
            });
        }
    }
}]);

Controller 2:

testApp.controller('SecondCtrl', ['$scope', '$modalInstance', 'namedList', 'selected', 'reqService', '$http'..., function (...){
   /*copy of the original items*/
   $scope.copyItem = angular.copy(selected);

   $scope.cancel = function () {
      $scope.selected = angular.copy($scope.copyItem);
      $modalInstance.dismiss('cancel');
   }

   $scope.reset = function () {
      $scope.selected = angular.copy($scope.copyItem);
      selected = angular.copy($scope.copyItem); //doesn't work
   }
}

My query is how can I refresh the tablelist? Upon clicking the reset button, it only resets the form in the modal window while the changes persist in the table list?! I'm unable to reset the "selected" variable in the resolve.

Answer №1

It seems like there may be a situation involving pass by value or pass by reference.
Check out this discussion on JavaScript's behavior .

It could be intriguing to experiment with passing a function that resets the value instead.

A potential approach

Controller 1:

$scope.open = function (item) {
    $scope.selectedItem = item;           
    modalService.openDialog($scope.namelist, function(e){
        if (e === undefined) {
            return $scope.selectedItem;
        } else {
            $scope.selectedItem = e;
        }
    });
}

Begin Controller 2 :

testApp.controller('SecondCtrl', ['$scope', '$modalInstance', 'namedList', 'selected', 'reqService', '$http'..., function (...){
    /*create a copy of the original items*/
   $scope.copyItem = angular.copy(selected());

   $scope.cancel = function () {
      $scope.selected = angular.copy($scope.copyItem);
      $modalInstance.dismiss('cancel');
   }

   $scope.reset = function () {
      $scope.selected = angular.copy($scope.copyItem);
      selected(angular.copy($scope.copyItem));
   }
}

I admit it's not the cleanest solution, but it serves as a test for the hypothesis.

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

Modifying attributes of an object within a document using Mongoose

Encountering an issue where the sentiment object in my document is not updating. Within my Model Class, there's a field named sentiment of type Object structured like this: sentiment: { terrible: 0, bad: 0, okay: 0, good: 0, fantastic: 0 } ...

How to dynamically assign a value in a React datepicker component in a React application

Having troubles with react-datepicker? I encountered an issue where setting the value of react-datepicker from props caused it to either not show the value or display a 'wrong time format' error. Here is a snippet of the Datepicker code: this.sta ...

Is there a way to make a text area box visible using JavaScript?

Currently, I am developing an automation script in Python using Selenium. My objective is to make a textarea box visible, as I need to insert some arguments into it. Here is the code snippet that I am utilizing: element = driver.find_element_by_id('g ...

Creating an interactive bootstrap modal: a step-by-step guide

For instance, I have 3 different tags with unique target-data for each one. <a class="btn btn-outline-primary btn-sm" href="#" data-toggle="modal" data-target="#firstdata"> DATA 1 </a> <a class=&q ...

"Learn how to easily send media files stored on your local server via WhatsApp using Twilio with Node.js and Express

Whenever I attempt to send the PDF file created through WhatsApp, an error pops up preventing me from viewing it. easyinvoice.createInvoice(data, function(result) { //The response will contain a base64 encoded PDF file ...

Customizing the Class of a jQuery UI ui-autocomplete Combobox Container

Is there a way to customize the ui-autocomplete div by adding a custom class? I have several autocomplete widgets on my webpage, and I need to style their drop-downs differently. Since editing the ui-autocomplete class directly is not an option, I am wor ...

Is there a way to trigger an angular function from an Android button when it is clicked?

Trying to incorporate an angular function into an Android application using webView.LoadUrl. The Android activity code being used is as follows: webView = (WebView) findViewById(R.id.webView1); webView.getSettings().setJavaScriptEnabled(true); webVi ...

The list of lists is giving an error: "Cannot read property 'name' of undefined."

What am I doing wrong here? let items = [{ name: 'client1' }, { name: 'client2' }, { name: "client3"}]; for (let i = 0; i < items.length; i++) { if (items[i]['name'].includes(self.autocomplete)) { self.box += '<l ...

Error: 'require' is undefined in react.production.min.js during production deployment

Greetings! I am encountering some difficulties while trying to build on production: the error "require is not defined" is being caused by react.production.min.js. Below are my webpack.config.js and package.json files: webpack.config.js const path = requi ...

Adjust size of item within grid component in VueJS

I have a grid container with cells and a draggable item in a Vue project. I am trying to figure out how to resize the box inside the grid component (refer to images). https://i.stack.imgur.com/q4MKZ.png This is my current grid setup, and I would like the ...

How does the useEffect React hook perform its comparison process?

One of my favorite JavaScript expressions is: []==[] // false Let's now explore what the React documentation says about skipping side effects: React allows you to skip applying an effect if certain values have not changed between re-renders. To a ...

Using JQuery's $.post function can be unreliable at times

Looking for help with a function that's giving me trouble: function Login() { var username = document.getElementById('username').value; var password = document.getElementById('password').value; $.post("Login.php", { ...

Jsx Component fails to display following conditional evaluations

One issue I am facing is having two separate redux stores: items (Items Store) quotationItems (Quote Items). Whenever a product item is added to quotationItems, I want to display <RedButton title="Remove" />. If the quotationItems store i ...

Multiple variable evaluation in Javascript does not function properly

Currently, I have an array that I am looping through in order to create variables. The variable names are derived from the array itself and I am using eval (only on my local machine) to achieve this. Interestingly, I can successfully create a variable and ...

Exploring the combination of Express router, Auth0, and plain Javascript: A guide to implementing post-login authentication on a router

After creating a front end with vite using vanilla javascript and setting up a backend with node.js express routes, I successfully integrated swagger for testing purposes. I have managed to enable functionalities such as logging in, logging out, and securi ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

Sort users by their data attribute using jQuery

I need to sort users based on their data attribute. Within the main div called user-append, I have a variable number of users retrieved from an ajax get request. It could be 3 users or even up to 100, it's dynamic. Here is the structure with one user ...

The importance of variables in Express Routing

I'm really diving into the intricacies of Express.js routing concepts. Here's an example that I've been pondering over: const routes = require('./routes'); const user = require('./routes/user'); const app = express(); a ...

jqGrid - Error when the length of colNames and colModel do not match!

Whenever I implement the code below, it triggers an error saying "Length of colNames and <> colModel!" However, if isUserGlobal is false, no errors occur. The version of jqGrid being used is 4.5.4 receivedColModel.push({name:'NAME', index: ...

Jquery events continue to accumulate without initiating until the preceding event has completed

Looking at the code below, it essentially fades all the images to 70% within the contact class. When an image is hovered over, its opacity changes to 100%. If multiple images are hovered over or multiple hover events occur in succession, the events will st ...