0

i write a simple angularJS code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.1/angular.min.js"></script>
</head>
<body ng-app="myApp">
  <script>
    angular.module('myApp', []).controller('BooksController', function($scope){
      $scope.books = [{'name':'aaa'}, {'name':'bbb'}, {'name':'ccc'}];
      $scope.addBook = function(newBook){
          $scope.books.push(newBook);
      }
    });
  </script>
  <div ng-controller="BooksController">
      <ul>
          <li ng-repeat="book in books">{{book.name}}</li>
      </ul>
      <input ng-model=aBook.name />
      <a href=# ng-click="addBook(aBook)">add to list</a>
  </div>
</body>
</html>

http://plnkr.co/edit/EIT32t8NgRiLchVXgooL?p=preview

when i add a new item to the list, it works correctly. but when i want to add another new item, the last item overwrite as you can see in the url. why? what happen?

2
  • Shouldn't it be: ng-model="book.name" instead of: ng-model=aBook.name Commented Feb 15, 2015 at 15:56
  • @Manube No, renaming aBook to book doesn't solve the problem as you can test at the address. Commented Feb 15, 2015 at 15:59

2 Answers 2

2

Try this way:

$scope.addBook = function(newBook){
    $scope.books.push(angular.copy(newBook));
}

why? what happen?

This happens because your input is bound to book's name, when you are adding book in array, same object instance is added, so binding is still happening.

before addBook()

$scope.books = [{'name':'aaa'}, {'name':'bbb'}, {'name':'ccc'}];

after addBook()

$scope.books = [{'name':'aaa'}, {'name':'bbb'}, {'name':'ccc'}, aBook];

With angular.copy we are creating another instance of book object with same property values

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

1 Comment

ok. so i prefer to empty the object of scope after add: $scope.books.push(newBook);$scope.aBook={}; thanks.
1
$scope.addBook = function(newBook){
      $scope.books.push($scope.newbook);
      $scope.newbook={"name":""};
      $scope.$apply();
  }
  $scope.newbook={"name":""};

and

<input ng-model="newbook.name" type="text">
  <a href=# ng-click="addBook()">add</a>

will work;

but when i want to add another new item, the last item overwrite as you can see in the url. why? what happen?

that's because a newbook has to be created right after insertion, with:

$scope.newbook={"name":""};

otherwise you will keep inserting/modifying the same item

2 Comments

i deleted my previous 'answer', as it was more a comment than anything else, as suggested by jsve
ok. so i prefer to empty the object of scope after add: $scope.books.push(newBook);$scope.aBook={}; thanks.

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.