Nicoleta Wilskon Nicoleta Wilskon - 1 month ago 6
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'];


Html:

<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>
</select>
</div>
<div class="form-group col-sm-2 col-xs-4">
<button ng-click="AddRole()">Click to Add Role</button>
</div>
</div>


JS:

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

$scope.AddRole = function(index) {
debugger;
if ($scope.model.role !== undefined) {
$scope.multiRoles.push($scope.model.role);
$scope.role.splice(index, 1);
console.log($scope.role);
}
};

Answer

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(){
          debugger;
          if($scope.model.role !== undefined ){
          $scope.multiRoles.push($scope.model.role);
          var index = $scope.role.indexOf($scope.model.role); //just find the right index which is the selected option in dropdown.
          $scope.role.splice(index,1);
                console.log($scope.role);
            }
        };