Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify object in angular js has changed

I have a backend object that i receive from the server and sent to server. I give a permission to my users to change the backend object. I would like to identify if the backend object has changed from the save point.

How can i identify it?

For example: I have a module called

app.controller('PanelCtrl', function($scope, $http) {
$scope.action = "";
$scope.selectedItem = "";
    $scope.compoundItem = [];

...

I have in the compound item array of Objects. I would like to know if something is changed whether the change occures in the primitives and whether in the compoundItem...

like image 717
Aviade Avatar asked Jan 11 '23 11:01

Aviade


1 Answers

Edit: two scenarios 1) client check (the original post) 2) server check (extended based on the comments)

1) check on the Client

do not worry about performance of the below steps. And if you do, please read more about performance here

The answer is: angular.equals() and a similar scenario is described here: Developer Guide / forms (it is about validation). In the section Binding to form and control state, we can see the script (an extract):

function Controller($scope) {
  $scope.master = {};

  $scope.update = function(user) {
    $scope.master = angular.copy(user);
  };

  $scope.reset = function() {
    $scope.user = angular.copy($scope.master);
  };

  $scope.isUnchanged = function(user) {
    return angular.equals(user, $scope.master);
  };
}

What we can see here, is what we need. Firstly copy the source state (inside the update function). We can change isUchnaged any time, while using the angular.equals()

Also check Compare objects in Angular

NOTE: A comment to the angular.copy(). I found, that in some cases, better is to use the lo-dash .deepClone()

2) Server side solution

In case that (as Dalorzo expects) are interesting in the comparison of the server, persisted version and the client. It could make sense, if we want to check if some one else has already changed the "Entity". In some other transaction

There are in general many techniques, but the most effective is versioning. On the persistence layer, we have to introduce some value, which is changed/incremented every time the "Update" is executed. In case of MS SQL Server it would be the rowversion, see more here

Then, during any sucesfull UPDATE operation, this version will be changed, and we know that data on the client are stale... there are newer on the server.

Summary with version:

Our check could be very easy:

  • Compare the Client (current) Version property and
  • ask the server for the latest persisted.

This is a standard way I am using with NHiberante (read more here)

like image 114
Radim Köhler Avatar answered Jan 17 '23 18:01

Radim Köhler