Search code examples
javascriptangularjsangular-ngmodel

Cannot push item to javascript array using ng-click if the ng-model does not change


I am able to add the items (through html input) to un-ordered list dynamically through ng-click event handling. This happens whenever i change the input textbox value. But if i click the add button without updating the textbox, the input textbox value is not added to list.

<body>
    <script>
        var app = angular.module("myShoppingList", []); 
        app.controller("myCtrl", function($scope) {
            $scope.products = ["Milk", "Bread", "Cheese"];
            $scope.addItem = function () {
                $scope.products.push($scope.addMe);
            }    
        });
    </script>

    <div ng-app="myShoppingList" ng-controller="myCtrl">
      <ul>
        <li ng-repeat="x in products">{{x}}</li>
      </ul>
      <input ng-model="addMe">
      <button ng-click="addItem()">Add</button>
    </div>

    <p>Write in the input field to add items.</p>
</body>

Solution

  • You need to add track by $index like following. AngularJS does not allow duplicates in a ng-repeat directive. You will get error if you try to do that.

    If you want to allow duplicate, you need to change your code like following.

       <li ng-repeat="x in products track by $index">{{x}}</li>
    

    Example

    var app = angular.module("myShoppingList", []);
    app.controller("myCtrl", function($scope) {
      $scope.products = ["Milk", "Bread", "Cheese"];
      $scope.addItem = function() {
        $scope.products.push($scope.addMe);
      }
    });
    <html>
    <head>
      <link rel="stylesheet" href="style.css">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
    </head>
    <body>
        <div ng-app="myShoppingList" ng-controller="myCtrl">
          <ul>
            <li ng-repeat="x in products track by $index">{{x}}</li>
          </ul>
          <input ng-model="addMe">
          <button ng-click="addItem()">Add</button>
        </div>
        <p>Write in the input field to add items.</p>
      </body>
    </html>