Search code examples
angularjscheckboxfirebaseangularfireremoveall

Angularfire remove items by checkbox


I am using Angularfire and I'd like to remove the items by checkbox.

And there is a button that can do the "checkAll" and another do the "uncheckAll"

HTML

<div ng-app="app" ng-controller="Ctrl">
  <li ng-repeat="item in newslist">
    <input type="checkbox"> {{item.newsTitle}}
  </li>
  <br>
  <button ng-click="checkAll()">check all</button>
  <button ng-click="uncheckAll()">uncheck all</button>
  <button ng-click="newslist.$remove(item)">Remove</button>
</div>

JS

var app = angular.module("app", ["firebase"]);
app.value('newsURL', 'https://XXX.firebaseio.com/XXX/');
app.factory('newsFactory', function($firebase, newsURL) {
  return $firebase(new Firebase(newsURL)).$asArray();
});
app.controller('Ctrl', function($scope, $firebase, newsFactory) {
  $scope.newslist = newsFactory;
  $scope.checkAll = function() {

  };
  $scope.uncheckAll = function() {

  };
});

plunker here

I don't know how to remove the items by checkbox or how to make the "checkAll" button work.

I will be appreciate if someone could tell me your answer.


Solution

  • Here is function you would need to check/uncheck and for removing items:

    $scope.checkAll = function() {
        $scope.newslist.forEach(function(el) {
            el.checked = true;
            $scope.newslist.$save(el);
        });
    };
    
    $scope.uncheckAll = function() {
        $scope.newslist.forEach(function(el) {
            el.checked = false;
            $scope.newslist.$save(el);
        });
    }
    
    $scope.remove = function() {
        $scope.newslist.forEach(function(item) {
            if (item.checked) {
                $scope.newslist.$remove(item);
            }
        });
    };
    

    Demo: http://plnkr.co/edit/GsGVsGGjNwW4i1kTOuko?p=preview

    I added checked property for ngModel directive.

    HTML becomes:

    <li ng-repeat="item in newslist">
        <input type="checkbox" ng-model="item.checked">{{item.newsTitle}}
    </li>
    
    <button ng-click="checkAll()">check all</button>
    <button ng-click="uncheckAll()">uncheck all</button>
    <button ng-click="remove()">Remove</button>