How do I bind to list of checkbox values with AngularJS?

前端 未结 29 2676
天涯浪人
天涯浪人 2020-11-22 05:20

I have a few checkboxes:





        
29条回答
  •  轮回少年
    2020-11-22 06:17

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


    With a simple array as input data

    The HTML could look like:

    
    

    And 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);
        }
      };
    }]);
    

    Pros: Simple data structure and toggling by name is easy to handle

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


    With an object array as input data

    The HTML could look like:

    
    

    And 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: Add/remove is very easy

    Cons: Somewhat more complex data structure and toggling by name is cumbersome or requires a helper method


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

提交回复
热议问题