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

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

I have a few checkboxes:





        
29条回答
  •  一向
    一向 (楼主)
    2020-11-22 06:09

    Here is yet another solution. The upside of my solution:

    • It does not need any additional watches (which may have an impact on performance)
    • It does not require any code in the controller keeping it clean
    • The code is still somewhat short
    • It is requires very little code to reuse in multiple places because it is just a directive

    Here is the directive:

    function ensureArray(o) {
        var lAngular = angular;
        if (lAngular.isArray(o) || o === null || lAngular.isUndefined(o)) {
            return o;
        }
        return [o];
    }
    
    function checkboxArraySetDirective() {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, element, attrs, ngModel) {
                var name = attrs.checkboxArraySet;
    
                ngModel.$formatters.push(function(value) {
                    return (ensureArray(value) || []).indexOf(name) >= 0;
                });
    
                ngModel.$parsers.push(function(value) {
                    var modelValue = ensureArray(ngModel.$modelValue) || [],
                        oldPos = modelValue.indexOf(name),
                        wasSet = oldPos >= 0;
                    if (value) {
                        if (!wasSet) {
                            modelValue = angular.copy(modelValue);
                            modelValue.push(name);
                        }
                    } else if (wasSet) {
                        modelValue = angular.copy(modelValue);
                        modelValue.splice(oldPos, 1);
                    }
                    return modelValue;
                });
            }
        }
    }
    

    At the end then just use it like this:

    
    

    And that is all there is. The only addition is the checkbox-array-set attribute.

提交回复
热议问题