How to bind to checkbox value list using AngularJS?

This article was translated from: How do I bind to list of checkbox values ​​with AngularJS?

I have a few checkboxes: I have a few checkboxes :

<input type='checkbox' value="apple" checked>
<input type='checkbox' value="orange">
<input type='checkbox' value="pear" checked>
<input type='checkbox' value="naartjie">

Would like the I to the bind That A to My List in the Controller that the WHENEVER SUCH IS A changed the CheckBox at The A List of the Controller Maintains at The All the checked values, for Example, ['apple', 'pear']. I would like to bind to list my controllers, so whenever When the check box is changed, the controller keeps a list of all checked values, for example ['apple', 'pear'].

ng-model seems to only be able to bind the value of one single checkbox to a variable in the controller. ng-model seems to only bind the value of one checkbox to a variable in the controller .

Is there another way to do it so that I can bind the four checkboxes to a list in the controller? Is there another way to bind the four check boxes to the list in the controller ?


#1st Floor

Reference: https://stackoom.com/question/ytsD/ How to use AngularJS to bind to checkbox value list


#2nd Floor

I think the easiest workaround would be to use 'select' with 'multiple' specified: I think the simplest solution is to use 'select' and specify 'multiple':

<select ng-model="selectedfruit" multiple ng-options="v for v in fruit"></select>

Otherwise, I think you'll have to process the list to construct the list (by $watch()ing the model array bind with checkboxes). Otherwise, I think you have to process the list to construct the list (through $watch()model array binding and checkboxes).


#3rd floor

<input type='checkbox' ng-repeat="fruit in fruits"
  ng-checked="checkedFruits.indexOf(fruit) != -1" ng-click="toggleCheck(fruit)">

.

function SomeCtrl ($scope) {
    $scope.fruits = ["apple, orange, pear, naartjie"];
    $scope.checkedFruits = [];
    $scope.toggleCheck = function (fruit) {
        if ($scope.checkedFruits.indexOf(fruit) === -1) {
            $scope.checkedFruits.push(fruit);
        } else {
            $scope.checkedFruits.splice($scope.checkedFruits.indexOf(fruit), 1);
        }
    };
}

#4th floor

Here's a quick little reusable directive that seems to do what you're looking to do. This is a quick and small reusable directive that seems to do what you want. I've simply called it checkList. I checkList simply called it . It updates the array when the checkboxes change, and updates the checkboxes when the array changes. It updates the array when the checkbox changes, and updates the checkbox when the array changes .

app.directive('checkList', function() {
  return {
    scope: {
      list: '=checkList',
      value: '@'
    },
    link: function(scope, elem, attrs) {
      var handler = function(setup) {
        var checked = elem.prop('checked');
        var index = scope.list.indexOf(scope.value);

        if (checked && index == -1) {
          if (setup) elem.prop('checked', false);
          else scope.list.push(scope.value);
        } else if (!checked && index != -1) {
          if (setup) elem.prop('checked', true);
          else scope.list.splice(index, 1);
        }
      };

      var setupHandler = handler.bind(null, true);
      var changeHandler = handler.bind(null, false);

      elem.bind('change', function() {
        scope.$apply(changeHandler);
      });
      scope.$watch('list', setupHandler, true);
    }
  };
});

Here's a controller and a view that shows how you might go about using it. This is a controller and a view that shows how to use it.

<div ng-app="myApp" ng-controller='MainController'>
  <span ng-repeat="fruit in fruits">
    <input type='checkbox' value="{{fruit}}" check-list='checked_fruits'> {{fruit}}<br />
  </span>

  <div>The following fruits are checked: {{checked_fruits | json}}</div>

  <div>Add fruit to the array manually:
    <button ng-repeat="fruit in fruits" ng-click='addFruit(fruit)'>{{fruit}}</button>
  </div>
</div>
app.controller('MainController', function($scope) {
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
  $scope.checked_fruits = ['apple', 'pear'];
  $scope.addFruit = function(fruit) {
    if ($scope.checked_fruits.indexOf(fruit) != -1) return;
    $scope.checked_fruits.push(fruit);
  };
});

(The buttons demonstrate that changing the array will also update the checkboxes.) (The buttons demonstrate that changing the array will also update the checkboxes .)

A finally, here Wallpaper Example of IS AN ON Plunker at The Directive in Action: http://plnkr.co/edit/3YNLsyoG4PIBW6Kj7dRK?p=preview Finally, this is an example of instruction on the Plunker: HTTP : //plnkr.co/edit/ 3YNLsyoG4PIBW6Kj7dRK? p = preview


#5th Floor

There are two ways to approach this problem. There are two ways to approach this problem . Either use a simple array or an array of objects. Use a simple array or an array of objects . Each solution has it pros and cons. Each solution has its advantages and disadvantages. Below you'll find one for each case. Below you will find one for each case .


With a simple array as input data with input data array as a simple

The HTML could look like: HTML may look like this:

<label ng-repeat="fruitName in fruits">
  <input
    type="checkbox"
    name="selectedFruits[]"
    value="{{fruitName}}"
    ng-checked="selection.indexOf(fruitName) > -1"
    ng-click="toggleSelection(fruitName)"
  > {{fruitName}}
</label>

And the appropriate controller code would be: The appropriate controller code would be :

app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {

  // Fruits
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];

  // Selected fruits
  $scope.selection = ['apple', 'pear'];

  // Toggle selection for a given fruit by name
  $scope.toggleSelection = function toggleSelection(fruitName) {
    var idx = $scope.selection.indexOf(fruitName);

    // Is currently selected
    if (idx > -1) {
      $scope.selection.splice(idx, 1);
    }

    // Is newly selected
    else {
      $scope.selection.push(fruitName);
    }
  };
}]);

The Pros : Toggling by the Simple Data Structure and name IS Easy to handle advantages : simple data structure and easy to handle handover by name

Cons : Add / remove is cumbersome as two lists (the input and selection) have to be managed Disadvantages : adding / removing is cumbersome because two lists must be managed (input and selection)


With an object array as input data used as input data array objects

The HTML could look like: HTML may look like this:

<label ng-repeat="fruit in fruits">
  <!--
    - Use `value="{{fruit.name}}"` to give the input a real value, in case the form gets submitted
      traditionally

    - Use `ng-checked="fruit.selected"` to have the checkbox checked based on some angular expression
      (no two-way-data-binding)

    - Use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected`
      is arbitrary. The property name could be anything and will be created on the object if not present.
  -->
  <input
    type="checkbox"
    name="selectedFruits[]"
    value="{{fruit.name}}"
    ng-model="fruit.selected"
  > {{fruit.name}}
</label>

And the appropriate controller code would be: The appropriate controller code would be :

app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) {

  // Fruits
  $scope.fruits = [
    { name: 'apple',    selected: true },
    { name: 'orange',   selected: false },
    { name: 'pear',     selected: true },
    { name: 'naartjie', selected: false }
  ];

  // Selected fruits
  $scope.selection = [];

  // Helper method to get selected fruits
  $scope.selectedFruits = function selectedFruits() {
    return filterFilter($scope.fruits, { selected: true });
  };

  // Watch fruits for changes
  $scope.$watch('fruits|filter:{selected:true}', function (nv) {
    $scope.selection = nv.map(function (fruit) {
      return fruit.name;
    });
  }, true);
}]);

Pros : the Add / IS the Remove the Easy Very advantages : add / remove very simple

Cons : Somewhat more complex data structure and toggling by name is cumbersome or requires a helper method Disadvantages : More complex data structures and switching by name are troublesome or need help methods


Demo : http://jsbin.com/ImAqUC/1/ Demo : http : //jsbin.com/ImAqUC/1/


#6th floor

Since you accepted an answer in which a list was not used, I'll assume the answer to my comment question is "No, it doesn't have to be a list". Since you accepted the answer to the unused list, I will Suppose the answer to my comment question is "No, it doesn't have to be a list". I also had the impression that maybe you were rending the HTML server side, since "checked" is present in your sample HTML (this would not be needed if ng-model were used to model your checkboxes). I also had such an impression, maybe You are rendering the HTML server side because there is "checked" in the sample HTML (if you use ng-model to model checkboxes, you don't need to do this).

Anyway, here's what I had in mind when I asked the question, also assuming you were generating the HTML server-side: Anyway, this is what I thought when I asked this question, also assuming that you are generating HTML server-side:

<div ng-controller="MyCtrl" 
 ng-init="checkboxes = {apple: true, orange: false, pear: true, naartjie: false}">
    <input type="checkbox" ng-model="checkboxes.apple">apple
    <input type="checkbox" ng-model="checkboxes.orange">orange
    <input type="checkbox" ng-model="checkboxes.pear">pear
    <input type="checkbox" ng-model="checkboxes.naartjie">naartjie
    <br>{{checkboxes}}
</div>

ng-init allows server-side generated HTML to initially set certain checkboxes. ng-init allows server-side generated HTML to initially set certain checkboxes .

Fiddle . Violin .

Published 0 original articles · praised 8 · 30,000+ views

Guess you like

Origin blog.csdn.net/asdfgh0077/article/details/105536942