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

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

I have a few checkboxes:





        
29条回答
  •  难免孤独
    2020-11-22 06:26

    There is a way to work on the array directly and use ng-model at the same time through ng-model-options="{ getterSetter: true }".

    The trick is to use a getter/setter function in your ng-model. This way you can use an array as your real model and "fake" the booleans in the input's model:

    
    

    $scope.fruits = ['apple', 'pear']; // pre checked
    
    $scope.fruitsGetterSetterGenerator = function(fruitName){
        return function myGetterSetter(nowHasFruit){
            if (nowHasFruit !== undefined){
    
                // Setter
                fruitIndex = $scope.fruits.indexOf(fruit);
                didHaveFruit = (fruitIndex !== -1);
                mustAdd = (!didHaveFruit && nowHasFruit);
                mustDel = (didHaveFruit && !nowHasFruit);
                if (mustAdd){
                    $scope.fruits.push(fruit);
                }
                if (mustDel){
                    $scope.fruits.splice(fruitIndex, 1);
                }
            }
            else {
                // Getter
                return $scope.user.fruits.indexOf(fruit) !== -1;
            }
        }
    }
    

    CAVEAT You shouldn't use this method if your arrays are big as myGetterSetter will be called a lot of times.

    For more on that, see https://docs.angularjs.org/api/ng/directive/ngModelOptions.

提交回复
热议问题