I do an educational (for myself) task with the purpose of studying, consolidating the material. Used by Angular + REST

The main page accesses the server and receives an array of data (for clarity, $ scope.messages), for example messages. Angular we deduced them in the table, in the table there is link Edit, when clicking the window with the data of this message gets out.

index.html

<form role="form" class="form-inline"> <div class="form-group"> <div class="col-lg-12"> <label class="control-label col-lg-4">Name</label> <input type="text" class="form-control text-area col-lg-8" id="inputName" ng-model="current.author"> </div> <div class="col-lg-12"> <label class="control-label col-lg-4 text-area-margin">Message</label> <textarea class="form-control text-area col-lg-7" rows="3" ng-model="current.message"></textarea> </div> <div class="col-lg-12 text-area-margin"> <button type="button" class="btn btn-default text-area-button" ng-click="closeEditFrame()">Cancel</button> <button type="submit" class="btn btn-default text-area-button" ng-click="saveEditedMessage(current)">Save</button> </div> </div> </form> 

script.js

  $scope.editMessage = function (data) { $scope.current = data; $scope.showEditFrame = true; } $scope.saveEditedMessage = function (data) { $http({ method: 'PUT', url: $scope.url + 'message/' + data.id, data: data, headers: {'Content-Type': 'application/json'} }).success(function (response) { console.log(response); $scope.showEditFrame = false; }, function (response) { console.log(response); }); } 

I’m missing the function to get all the data, it’s not important here.

So everything works, but there is such a moment, if I change the data on the client side and do not save it, but I’ll click cancel, they will be saved in scoop and displayed as changed, the same happens if for some reason they are not saved on the server. Obviously, the ng-model is not suitable here, what is appropriate? And how to properly organize this relationship between client and server? Approximately the same question I have for the date of the message change, should the server or client generate it?

    1 answer 1

    Correct answer

      $scope.editMessage = function (data) { $scope.current = angular.copy(data); $scope.showEditFrame = true; } 

    And then we work with a copy.

    • I would not say that this is the best option, but it is quite suitable. - Qwertiy
    • I have not yet found another, but no one suggests anything better. - Sergei R
    • Make a directive that will require ngModel on the whole entity, copy it, and re-assign it while saving. - Qwertiy
    • I have not yet reached the directives in the process, but if there are examples, I will be glad. - Sergei R