Nicolas
Nicolas

Reputation: 155

Angular - set null items in array

Why is this code working only once? When i reset an item the entire app freezes

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<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);
    }    
    $scope.resetItem = function (x) {
        $scope.products[x]="";
    }
});
</script>

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

<p>Click the x to reset an item</p>

</body>
</html>

I've also tryed with ng-click='x = "" ' but it doesn't work. So, how can I set a null value to an item in this array?

Upvotes: 0

Views: 2188

Answers (2)

epascarello
epascarello

Reputation: 207511

If you want to remove an item. You can remove it from the array with splice(index, numberOfItemsToRemove)

$scope.products.splice(x, 1)

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41407

use track by $index in ng repeat to remove the duplicate.

Also use splice to remove the item from an array

var app = angular.module("myShoppingList", []); 
app.controller("myCtrl", function($scope) {
    $scope.products = ["Milk", "Bread", "Cheese"];
    $scope.addItem = function () {
        $scope.products.push($scope.addMe);
    }    
    $scope.resetItem = function (x) {
         $scope.products.splice(x,1);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
 
  <ul>
    <li ng-repeat="x in products track by $index">{{x}}<span ng-click="resetItem($index)">×</span></li>
  </ul>
  <input ng-model="addMe">
  <button ng-click="addItem()">Add</button>
</div>

<p>Click the x to reset an item</p>

Upvotes: 2

Related Questions