Set validity of multiple inputs from a AngularJS Directive

霸气de小男生 提交于 2019-12-05 07:59:54

I would try to approach this problem by implementing helper object to store group elements controllers with methods to add to the group and setValidity of all elements in the group.

Something like this:

angular.module('myModule').directive('groupedInputs', function() {

    var groupControls = {
        groups: {},
        add: function(name, ctrl) {
            this.groups[name] = this.groups[name] || [];
            this.groups[name].push(ctrl);
        },
        setValidity: function(name, key, value) {
            this.groups[name].forEach(function(ctrl) {
                ctrl.$setValidity(key, value);
            });
        }
    };

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, element, attrs, ctrl) {

            // Add element controller to the group
            groupControls.add(attrs.groupedInputs, ctrl);

            element.on('change', function() {

                // When needed, set validity of elements in the group
                groupControls.setValidity(attrs.groupedInputs, 'server', false);
                scope.$apply();

            });
        }
    };
});

Demo: http://plnkr.co/edit/fusaaN6k9J5SZ7iQA97V?p=preview

You could store all the controllers having the same group in an array:

angular.module('myModule').directive('groupedInputs', function () {
    var controllersPerGroup = {};

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ctrl) {
            var groupName = attrs.groupedInputs;
            var group = controllersPerGroup[groupName];
            if (!group) {
                group = [];
                controllersPerGroup[groupName] = group;
            }
            group.push(ctrl);

            element.on('change', function () {

                // Resetting own validity
                scope.$apply(ctrl.$setValidity('server', true));

                // all the other controllers of the same group are in the groups array.
            });
        }
    };
});

Don't forget to take care of removing the controllers once the element is destroyed, by listening to the $destroy event.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!