0

Hello I have created a button for add element in a list, but it add only one object, how can i do for add each object for each click on button ?

this is HTML

<body >
 <div  ng-controller="myControl">
  <ul>
    <li ng-repeat="x in products">{{x}}      
     <button ng-click="removeEle($index)"> X </button>
    </li>
  </ul>
  <button ng-click="addEle()"> add</button>

 </div>

and this is js

    var app = angular.module('myClick', []);

app.controller('myControl', ['$scope', function($scope){


   $scope.products=['one','two','three'];
    $scope.addEle= function(){
      $scope.products.push($scope.add);
  }
   $scope.removeEle =function(x){
     $scope.products.splice(x,1);
   }

}]);

thanks for help

1 Answer 1

1

<!DOCTYPE html>
<html data-ng-app="myClick">

<head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>

<body>
  <div ng-controller="myControl">
    <ul>
      <li ng-repeat="x in products track by $index">{{x}}
        <button ng-click="removeEle($index)">X</button>
      </li>
    </ul>
    <button ng-click="addEle()">add</button>
  </div>
  <script>
    var app = angular.module('myClick', []);

    app.controller('myControl', ['$scope',
      function($scope) {


        $scope.products = ['one', 'two', 'three'];
        $scope.addEle = function() {
          $scope.products.push($scope.add);
        }
        $scope.removeEle = function(x) {
          $scope.products.splice(x, 1);
        }

      }
    ]);
  </script>
</body>

</html>

Issue with your code is , you are trying to insert null element multiple times, and it is making duplicates in array.So issue can be fixed by adding track by with ng-repeat.(add valid elements in array to see correct data)

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

Comments

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.