how to prevent duplicate in array push in angularjs
Just javascript is enough.
If an array contains the item its index is >= 0
so you can do this, if index == -1 , item does not exist in the array, so you can push unique item
if(arr.indexOf(item) == -1) { arr.push(item);}
Edit: You asked for changing the number, this is how
var index = arr.indexOf(item);if(index > -1) { //checking if item exist in array arr[index]++; // you can access that element by using arr[index], // then change it as you want, I'm just incrementing in above example}
As what most of the answers have pointed out, you can use the Array.prototype.indexOf()
method to determine if a value exists or not. In order to check for this, check the array of strings against your ng-models
value property, selects.value
, within the ng-change()
event callback.
Javascript
$scope.goChange = function(name, value){ if(!~arr.indexOf(value)) { arr.push(name, value); console.log(arr); }};
HTML
<select ng-model="selects" ng-change="goChange(item.name, selects.value)" ng-options="i as i.value for i in options"> <option value=""></option></select>