What is the most effective way to update a variable from a function in Angular?

I have textboxes within an ng-repeat block. To detect changes from the original content, I store the original data in a variable.

<tr data-ng-repeat="p in products">
  <td>
    <textarea data-elastic data-ng-model="p.comment" data-ng-change="hasChanged=checkChange(original, rnd.comment);" data-ng-init="original=rnd.comment; hasChanged=false"></textarea>
  </td>
  <td class="save" ng-show="hasChanged" ng-click="save(p, original)">Save</td>

A save button is displayed only when there are changes in the content. After a successful save, the original value should be updated to the new value.

To achieve this, I use a function in the controller:

$scope.save = function (p, original) {
  //...successful save
  this.original = p.comment; //this method works
  original = p.comment; //this method does not work
}

Relying on 'this' for implicit scope doesn't seem like the best approach.

Why doesn't updating the variable (original = ...) work? Is there a better way to handle this?


After considering comments, I made the following updates:

ng-click="save(p, this)"

$scope.save = function (p, scope) {
 //...successful save
 scope.original = p.comment; //this method works
}

This approach seems more reasonable now. However, is passing scope around like this considered bad practice or acceptable?


The 'products' data is defined as follows:

productStatusApp.controller('productStatusCtrl', function ($scope, $http, cid) {
   $http.get('api/company/products/' + cid).success(function (data) {
      $scope.products = data.products;
   });

Answer №1

To steer clear of these types of issues, I've discovered that utilizing services is the way to go.

Check out this resource on AngularJS services

Here's a tutorial on AngularJS service factories

Here's some basic code (for reference only, not thoroughly tested):

<tr data-ng-repeat="p in ProductsService.products">
   <td>
       <textarea data-elastic data-ng-model="p.comment"></textarea>
   </td>
   <td class="save" ng-show="p.originalComment!==p.comment" ng-click="ProductsService.save(p)">Save</td>
</tr>

Plus:

var module = angular.module('app', []);
module.service('ProductsService', function () {
   var products = [postA, postB, ..., PostC];

   products = products.map(function(p){p.originalComment=p.comment});

   var save = function(p){
         p.originalComment=p.comment;
         someAjaxRequest(function _callback(err,response){....})
   }

   return {products:products, save:save};
});

Also:

module.controller('ProductsController', function ($scope, ProductsService) { 
    $scope.ProductsService = ProductsService;
});

Using services not only enhances readability but also ensures a win-win situation.

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 variable remains unchanged after the API call, despite using useState

Despite my efforts to find a solution, I still find myself puzzled by this question that has seemingly been answered before. The issue lies in the synchronization of my code when making a request to the what3words API. The data retrieved is assigned to a ...

Utilize the current window in a new tab

In my main page named 'main.html', I have a link that opens a popup or focuses on an existing popup using the following code snippet: var test; if (test == null || test.closed) test = window.open('test.html','test','width ...

Using Material UI's ProgressBar to create a countdown feature in a React

I am working on a feature where pressing a lock button changes the isReserved status of an item to true. This action also creates two new states in Firebase Firestore, namely startDate and expiryDate. The expiryDate is set to be 72 hours after the startDat ...

The synergy of Redux with scheduled tasks

In order to demonstrate the scenario, I have implemented a use-case using a </video> tag that triggers an action every ~250ms as the playhead moves. Despite not being well-versed in Flux/Redux, I am encountering some challenges: Is this method cons ...

What are the steps to organize an array of objects by a specific key?

Experimented with the following approach: if (field == 'age') { if (this.sortedAge) { this.fltUsers.sort(function (a, b) { if (b.totalHours > a.totalHours) { return 1; } }); this ...

Exploring the differences between React state and CSS :hover in the context of a dropdown menu that is accessible to both desktop users (via mouse) and

I have come across a dilemma regarding a dropdown menu that needs to cater to both Desktop/PC users (with mouse) and Mobile devices (with touch). After considering my options, here are the proposed solutions: OPTION 1 One approach is to implement it usi ...

Capture a photo within your app using the Cordova Camera plugin and seamlessly upload it to Parse.com platform

I am currently in the process of developing an app using Ionic/Cordova that utilizes Parse.com as a Backend as a Service. The app integrates the ngCordova Camera plugin for managing the device camera functionality. The main objective is to enable users to ...

Using Try...catch compared to .catch

Within my service.ts file, I have various user service functions that handle database operations. export const service = { async getAll(): Promise<User[]> { try { const result = await query return result } catch (e) { rep ...

Abnormal scrolling issues observed on handheld devices like mobile phones and tablets

I recently added a parallax effect to the hero section of my website, and while it works perfectly on desktop, I encountered some scrolling issues when viewing it on mobile or tablet devices. Sometimes the scrolling behaves as intended, and other times it ...

Exploring search capabilities within D3 graph nodes

After creating a JSON file with four tiers and utilizing D3.js's collapsing box format to visualize it (source: https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460), I've run into an issue. The problem stems from the sheer size of the J ...

Authentication through Google and Twitter

I'm looking to incorporate Google and Twitter login buttons on my website without the need for server-side code. Unfortunately, I haven't been able to find any APIs that allow for this without a secret key. Do you have any suggestions or ideas on ...

vaadin-grid selection issue not functioning

I'm encountering an issue with the row selection feature. The selectedItems array only updates when I select all items at once. I'm not sure if I'm missing something or if this is a bug. selectedItems: An array that contains the selected ...

Having difficulty retrieving model values from the angular ui modal dialog

Being only on my second day in the world of Angular, I am trying to navigate around Angular UI and build my first modal dialog. The modal dialog displays properly, but I'm encountering an issue with using models within it. You can view my demo on Plun ...

In JavaScript, the Else statement fails to run

Hi there, I'm currently working on creating a function to check the validity of a string input. This is what I have so far: function validatePassword(){ passW = prompt ("Enter Password:"); if (passW == 'Pass123'){ document.write ('Y ...

Tips for choosing multiple checkboxes with the input type of "checkbox"

image of my columns and checkboxes <table class="table table-striped grid-table"> <tr> <th>Id</th> <th>Code</th> <th> <input type="checkbox" id="box&q ...

Guide on exporting a function from a module as a class property

How to export a function as a class property from a module? Even if modifiers such as public are added, when a class property points to a function within a module, it behaves as though it is private. There are multiple ways to define a property (a, b, c ...

Validating fields using JavaScript and HTML

I'm having an issue with the code below because it only allows me to log in with the user and password from the last position of the arrays. I want it to let me login with each user and their corresponding password, for example, user at position 1 wit ...

PHP-based user interface queue system

I am in the process of developing a website that enables users to manipulate a webcam by moving it from left to right. Each user will have a one-minute window to control the camera. I plan on implementing a queuing system on the site to ensure that users ...

Filling out the form will automatically direct you to the text input section

I'm trying to figure out if I can create an input box in HTML that directs the user to a specific HTML file based on the word they enter. For example, if they type "Doctor", it would redirect them to the page doctor.html. This is for a school project ...

Emit data asynchronously upon returning

In my node.js application, I have a background process implemented using the EventEmitter. Here is a snippet of how it is used: var event = { returnValue: undefined }; eventEmitter.emit('name', event, argument); return event.returnValue; // This ...