0

I'm trying to edit list items in the same input field I use for adding items.

Have a look at

http://jsbin.com/retadexu/188/edit

and

http://jsbin.com/retadexu/192/edit

The first example works, but I have to assign the temporary object's .name property to the list object:

$scope.currentItem.name = $scope.newToDo.name;

The second, where I assign the whole object, doesn't work:

$scope.currentItem = $scope.newToDo;

So if I had more than just the "name" property, do I really have to assign all values?

1 Answer 1

1

Instead of keeping track of the current by the object, keep track of the index in the array of that item.

$scope.saveTodo = function(todo) {
  if ($scope.editMode) {
    $scope.currentItem = $scope.newToDo;
    $scope.todos[$scope.currentItemIndex] = $scope.newToDo;
    $scope.editMode = false;
  } else {
    $scope.todos.push($scope.newToDo);
  }
  $scope.newToDo = "";
};

$scope.editTodo = function(todo) {
  $scope.editMode = true;
  $scope.newToDo = angular.copy(todo);
  $scope.currentItemIndex = $scope.todos.indexOf(todo);
};

I also moved the text of the button into the markup rather than the controller (personal preference)

<button ng-click="saveTodo(todo)">{{editMode ? 'Edit' : 'Add'}}</button>

See it working in this plnkr

Sign up to request clarification or add additional context in comments.

1 Comment

I also renamed the addTodo function to be saveTodo as it serves both purposes (add/edit)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.