1

I have an ng-repeat with a select in every item.

The user can select a value (trigging a function that pushes the an object into an array), but they can also change their mind, in which case the code just pushes a second object with the new value, duplicating the first one.

How could I manage to actually delete existing values, leaving only the last one on every ng-change?

Here's my HTML:

<select ng-change="insertproduct(pa.nom, basket)" ng-model="basket">
  <option ng-repeat="select in numberofproducts">{{select}}</option>
</select>

And my javascript:

$scope.numberofproducts = [1,2,3,4,5,6,7,8,9,10]

$scope.singleorder = [];

$scope.insertproduct = function(nom, basket){
  $scope.numero = {
    'producte': nom,
    'numero': basket
  };
  $scope.singleorder.push($scope.numero);
  console.log($scope.singleorder);
}

The idea is to create a condition in which if the array contains an object with the parameter ´producte´ equal to the new one, delete the existing and push the new one.

Any tips?

2 Answers 2

0

First, use the findIndex method to check if an object with the same property is already in the singleorder array.

function duplicateOrder(order) { 
    return order.producte === nom;
}
var index = $scope.singleorder.findIndex(duplicateOrder);

Note: browser support for findIndex is limited; it is not supported in Internet Explorer.

Then remove the item with splice:

if(index > -1){
$scope.singleorder.splice(index, 1);
}

You can then push the new one in.


You should also clean up your coding style: don't mix french and english, and use either camelCase or snake_case for your functions to improve readability.

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

Comments

0

Observation :

  • Use AngularJS ngOptions attribute instead of ng-repeat.
  • You can check the index of the element in an array if that was already there you can easily remove previous one.

DEMO

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

myApp.controller('MyCtrl',function($scope) {
    $scope.numberofproducts = [1,2,3,4,5,6,7,8,9,10]

    $scope.newArray = [];

    $scope.insertproduct = function(basket) {
      var prevIndex = $scope.newArray.indexOf(basket);
      if(prevIndex > -1) {
        $scope.newArray.splice(prevIndex, 1);
      } else {
        $scope.newArray.push(basket);
      }
      console.log($scope.newArray);
    }
   
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
 <select ng-change="insertproduct(basket)" ng-model="basket" ng-options="select for select in numberofproducts">
</select>
</div>

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.