Nicoleta Wilskon Nicoleta Wilskon - 1 year ago 58
AngularJS Question

How to remove item from an array

I have a dropdown where items are populated from $scope.role. Now I need to remove the values from $scope.role once the value is added or selected in dropdown. I did splice(index,1) which actually delete the first element only. Need assistance.

$scope.role = ['Actor', 'Director/ Asst. director', 'Lyricist',
'Music director/ Asst. director', 'Singer', 'Standup Comedian', 'Model',
'Cinematographer', 'Photographer', 'Script Writer', 'Choreographer',
'Editor/ Promo editor', 'Costume designer', 'Art director', 'Stunt artist',
'Voice-over artist', 'Graphic Designer', 'Screenplay', 'Dialogue',
'Back ground music'];


<div class="row newRow">
<div class="form-group fields col-sm-2 col-xs-4">
<label>ROLE *</label>
<select name="role" class="form-control1 drop2" required ng-model="model.role" placeholder="select">
<option value='' disabled selected>Select</option>
<option ng-repeat="item in role track by $index" value="{{item}}">{{item}}</option>
<div class="form-group col-sm-2 col-xs-4">
<button ng-click="AddRole()">Click to Add Role</button>


$scope.multiRoles = [];
$scope.role == $scope.dummy;
$scope.rolesAdded = false;

$scope.AddRole = function(index) {
if ($scope.model.role !== undefined) {
$scope.role.splice(index, 1);

Answer Source

You can do it in two ways 1) As suggested by @nikjohn by sending your $index of dropdown in ng-click = "AddRole($index)" and then splice or else

2) You can find the index of the selected option by using the ng-model binded to the dropdown.

     $scope.AddRole = function(){
          if($scope.model.role !== undefined ){
          var index = $scope.role.indexOf($scope.model.role); //just find the right index which is the selected option in dropdown.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download