swetha
swetha

Reputation: 65

How edit functionality update its value in frontend in angularjs?

I am trying to write edit functionality in angularjs. It almost has done. But the value is not updated in view part. Can anyone help? My code is given below Am using ng-repeat="book in books"

Html

 <li ng-click="delegate.editPost()">Edit</li>
 <div ng-show="showEditPost">
   <div ng-click="delegate.savePost()">Save</div>
   <p ng-if="showEditPost==false">{{book.text}}</p>
   <div ng-if="showEditPost == true">
      <textarea >{{edit.text}}</textarea>
   </div>
 </div>

controller

    editPost:function(){
            $scope.showEditPost=true;
            $scope.edit=angular.copy($scope.books);
        },
       save:function(){
            var Obj = {
                text: $scope.edit.text
            }
            editService.edit( Obj,this.onSuccess, this.onFailure);
        },

    onSuccess:function(){

            $scope.showEditPost=false;
            angular.copy($scope.edit,$scope.books);
        }

Upvotes: 0

Views: 255

Answers (1)

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

I think you are making it too complicated. But instead of working with entire arrays, you should be passing the index and working with individual elements. Here is a simple demo:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.books = [{
    "text": "Book 1"
  }, {
    "text": "Book 2"
  }];
  $scope.showEditPost = $scope.books.map(function(_) {
    return false;
  }); // populating array with `false` values
  
  $scope.editPost = function(index) {
    $scope.showEditPost[index] = true;
    // edit is now an element and not an entire array 
    $scope.edit = angular.copy($scope.books[index]);
  }
  $scope.savePost = function(edit, index) {
    $scope.books[index] = edit;
    $scope.showEditPost[index] = false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
<!-- 
`track by $index` is added to allow repetition/duplicates
-->
  <div ng-repeat="book in books track by $index">
    <!-- passing index with `$index` -->
    <button ng-click="editPost($index)">Edit</button>
    <!-- editing only an individual box by using index -->
    <p ng-if="!showEditPost[$index]">{{book.text}}</p>
    <div ng-if="showEditPost[$index]">
      <button ng-click="savePost(edit,$index)">Save</button><br>
      <!-- `ng-model` is added to allow modification -->
      <textarea ng-model="edit.text">{{edit.text}}</textarea>
    </div>
  </div>

</div>

Upvotes: 1

Related Questions