【问题标题】:required on custom directive select需要自定义指令选择
【发布时间】:2014-12-16 09:03:17
【问题描述】:

我使用无序列表和 ng-repeat 创建了自己的选择下拉菜单。 该指令的问题在于它不能作为普通的 select/input/textarea 工作,您可以在 html 表单中使用它时使用 required 。

那么,如何通过自定义指令的验证来实现选项 required/ng-required(作为指令)?

我应该使用自己的验证实现吗?

dropdown.html

<!-- displayed text on the select -->
<div class="title"
     ng-class="{'placeholder': !hasSelected(), 'selected': isOpened}"
     ng-mousedown="openSelect()">
    {{getTitle()}}

    <div class="icon" ng-class="{'active': isOpened}">
        <i class="fa fa-caret-down"></i>
    </div>
</div>

<!-- displayed options when opening the select dropdown -->
<div class="options">
    <ul ng-show="isOpened">

        <!-- First option is only shown when an empty option is required -->
        <li ng-click="select(null)"
            ng-show="hasEmptyOption() && isSelected()"
            class="empty">
            {{empty}}
        </li>

        <!-- Options of the select -->
        <li ng-repeat="option in options track by $index"
            ng-click="select($index)"
            ng-class="{'active': isActive($index)}">
            {{option}}
        </li>
    </ul>
</div>

dropdown.js

app.module.directive('dropdown', ['$document',
    function ($document) {
        'use strict';

        return{
            restrict: "E",
            scope: {
                model: "=",
                empty: "@",
                message: "@",
                options: "="
            },
            templateUrl: 'app/common/directive/dropdown/dropdown.partial.html',
            link: function (scope, elem, attrs) {
                scope.message = "My message";
                scope.isOpened = false;

                scope.isSelected = function () {
                    return scope.model && scope.model !== null;
                };

                scope.hasEmptyOption = function () {
                    return scope.empty && scope.empty !== null;
                };

                scope.hasSelected = function () {
                    return (scope.selected);
                };

                scope.select = function (index) {
                    if (index !== null) {
                        scope.model = scope.options[index];
                    } else {
                        scope.model = null;
                    }
                    scope.closeSelect();
                };

                scope.closeSelect = function () {
                    scope.isOpened = false;
                    $document.unbind('click');
                    elem.unbind('click');
                };

                scope.openSelect = function () {
                    if (scope.isOpened) {
                        scope.closeSelect();
                    } else {
                        scope.isOpened = true;
                        $document.bind('click', function () {
                            scope.closeSelect();
                            scope.$apply();
                        });
                        elem.bind('click', function (e) {
                            e.stopPropagation();
                        });
                    }
                };

                scope.getTitle = function () {
                    if (scope.model && scope.model !== null) {
                        return scope.model;
                    } else if (scope.message) {
                        return scope.message;
                    } else {
                        return "Select";
                    }
                };
            }
        };
    }
]);

用法

<dropdown message="Select state" model="selectedState" options="states" empty="unselect"></dropdown>

预览

【问题讨论】:

    标签: angularjs angularjs-directive required


    【解决方案1】:

    我想我对这个问题有点太快了。对此感到抱歉。但答案对其他人非常有用

    用法

    <dropdown message="Select state" model="selectedState" options="states" empty="unselect" valid-drop-down></dropdown>
    

    validation_dropdown.js

    [EDIT] 稍微更改了指令以便更好地理解,添加注释

    /**
     * Based on
     * http://stackoverflow.com/questions/24692775/angularjs-setvalidity-causing-modelvalue-to-not-update
     */
    app.module.directive('validDropDown', [
        function () {
            return {
                require: 'ngModel',
                link: function (scope, elem, attr, ngModel) {
    
                    // Create validators
                    ngModel.$validators.validDropDown = function (modelValue, viewValue) {
                        /* When no value is present */
                        var isValid;
                        if (!modelValue || modelValue.length === 0) {
                            isValid = false;
                        } else {
                            isValid = true;
                        }
    
                        /* Set required validator as this is not a standard html form input */
                        ngModel.$setValidity('required', isValid);
    
                        /* Set custom validators */
                        ngModel.$setValidity('validDropDown', isValid);
    
                        /* Return the model so the model is updated in the view */
                        return modelValue;
                    };
    
                    // Watch for changes to the model
                    scope.$watch(attr.ngModel, function () {
    
                        /* When the model is touched before */
                        if (ngModel.$touched) {
                            /* When the model is not dirty, Set ngModel to dirty by re-applying its content */
                            if (!ngModel.$dirty) {
                                ngModel.$setViewValue(ngModel.$modelValue);
                            }
                        }
    
                        /* When the model has a value */
                        if (ngModel.$modelValue) {
                            /* When the model is not touched before */
                            if (!ngModel.$touched) {
                                ngModel.$setTouched();
                            }
                        }
    
                        return ngModel;
                    });
    
                    // Validate on creation
                    ngModel.$validate();
                }
            }
        }
    ]);
    

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 1970-01-01
      • 2015-12-04
      • 2019-12-01
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多