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

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

I have a few checkboxes:





        
29条回答
  •  被撕碎了的回忆
    2020-11-22 06:10

    Here's a quick little reusable directive that seems to do what you're looking to do. I've simply called it checkList. It updates the array when the checkboxes change, and updates the checkboxes 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.

    {{fruit}}
    The following fruits are checked: {{checked_fruits | json}}
    Add fruit to the array manually:
    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.)

    Finally, here is an example of the directive in action on Plunker: http://plnkr.co/edit/3YNLsyoG4PIBW6Kj7dRK?p=preview

提交回复
热议问题