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

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

I have a few checkboxes:





        
29条回答
  •  无人共我
    2020-11-22 06:11

    I like Yoshi's answer. I enhanced it so You can use the same function for multiple lists.

    
    
    
    
    
    
    
    app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
      // fruits
      $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
      $scope.veggies = ['lettuce', 'cabbage', 'tomato']
      // selected fruits
      $scope.selection = ['apple', 'pear'];
      $scope.veggieSelection = ['lettuce']
      // toggle selection for a given fruit by name
      $scope.toggleSelection = function toggleSelection(selectionName, listSelection) {
        var idx = listSelection.indexOf(selectionName);
    
        // is currently selected
        if (idx > -1) {
          listSelection.splice(idx, 1);
        }
    
        // is newly selected
        else {
          listSelection.push(selectionName);
        }
      };
    }]);
    

    http://plnkr.co/edit/KcbtzEyNMA8s1X7Hja8p?p=preview

提交回复
热议问题