简体   繁体   中英

Remove elements from array based on filter in angularjs

How can I remove elements from array based on a filter, remove only those indexes when 'quantity' is 0 and 'isSelected' is false? Any suggestion. Here is my code:

<table data-ng-repeat="st in Absorb track by $index" data-ng-cloak data-ng-init="remove(st)">                                          
    <tr>
        <td>                                                    
            <input type="radio" name="groupName" data-ng-model ="st.isSelected" data-ng-checked="(st.isSelected == true)"/>
        </td>
        <td>                                                       
            <span>{{st.ProjectedQuantityOnHand}}</span>
        </td>
        <td style="display:none" data-ng-if="st.ProjectedQuantityOnHand == 0">                                                       
            <input type="number" data-ng-model="st.ProjectedQuantityOnHand" style="display:none">
        </td>
    </tr>
</table>

JS code:

$scope.Absorb = [
    {"Name":"apple", ProjectedQuantityOnHand:"0", isSelected:true},
    {"Name":"mango", ProjectedQuantityOnHand:"0", isSelected:false}
    {"Name":"ball", ProjectedQuantityOnHand:"1", isSelected:false}
    {"Name":"football", ProjectedQuantityOnHand:"1", isSelected:false}
]

$scope.remove = function (item) {
     var availableqauantity = 0
     debugger
     angular.forEach($scope.StockList, function (i) {
        var FilteredProduct1 = $filter('filter')($scope.StockList, { isSelected: false, ProjectedQuantityOnHand: 0 });
        if (FilteredProduct1.length > 0) {
            availableqauantity = FilteredProduct1[0].ProjectedQuantityOnHand;
        if (availableqauantity == 0)
            $scope.StockList.splice(i,1);
        }
     });
}
<table data-ng-repeat="st in Absorb | filter:{isSelected: '!false', ProjectedQuantityOnHand: '!0'} track by $index" data-ng-cloak> 

This will show only those items, which have isSelected different than false and ProjectedQuantityOnHand different than 0. No need for external function.

UPDATE

https://plnkr.co/edit/gPz5pKSIOxZ6odSU3TfF?p=preview

Check this example. Here I've made a custom filter to hide items only when ProjectedQuantityOnHand is 0 and isSelected is false.

app.filter('customFilter', function() {
  return function(values) {
    var filtderResult = [];
    angular.forEach(values, function(value) {
      if (value.isSelected || value.ProjectedQuantityOnHand !== 0) {
        filtderResult.push(value);
      }
    });
    return filtderResult;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM