Search code examples
angularjsangularjs-directiveangularjs-scopeangular-ui-router

angular checkbox list manipulation


I have multiple columns in my list and I want to add checkboxes to my index. I want to be able to check the boxes to get the filtered list and when uncheck them, of course it should give me the correct result. I am not sure the best way to achieve that. some posts were talking about watcher and others were suggestion just array of data to push to. I tried pushing to an array and then set it to $scope.cars but the problem is that it is just too much work to get back my original $scope.car. So I dropped that idea. Now I am waiting for a better solution. Here is my code

script.js

// Code goes here

var app = angular.module('myapp', []);

app.controller('DemoCtrl', [ '$scope', function($scope) {
  $scope.q = '';
  $scope.cars = [
  {
    year: 2006,
    make: 'BMW',
    model: 'M3'
  },
  {
    year: 2006, 
    make: 'BMW',
    model: 'Z4'
  },
  {
    year: 1992, 
    make: 'Mazda',
    model: 'Miata'
  },
  {
    year: 2008, 
    make: 'BMW special',
    model: '750'
  }
  ];


}]); 

index.html

<!DOCTYPE html>
<html ng-app="myapp">

  <head>
    <link data-require="[email protected]" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="DemoCtrl">

        <input type="checkbox">BMW
        <span style="margin-left:20px;"></span><input type="checkbox">Mazda</span>


      <input class="form-control" type="text" ng-model="q" placeholder="Search by year, make, model" />
      <br/>
      <ul>
        <li ng-repeat="car in cars | filter:filterCars">{{car.year}} {{car.make}} {{car.model}}</li>
      </ul>
    </div>
  </body>

</html>

and her eis plunker http://plnkr.co/edit/QXPYKBkH6u7N374yjQHV?p=preview

thanks


Solution

  • You can do this by setting ng-model on checkboxes and using that model in ng-repeat filter

    <input type="checkbox" ng-model="filters.mfgr" ng-true-value="BMW"  ng-false-value="">
    
    <li ng-repeat="car in cars | filter:{make:filters.mfgr}">
    

    To combine the text search and checkboxes make a custom filter that accepts both models as arguments

    DEMO