How to add / set checks (require, prestine, etc.) in custom angular directives

I created the angular directive as follows:

angular.module('SharedModule')
    .directive('multiSelect', ['$ionicModal', multiSelect]);


function multiSelect($ionicModal) {
    return {
        restrict: 'E',
        template: [
            '<div ng-click="showItems($event)" class="item-icon-right item">',
            '{{text}}',
            '<i class="icon ion-ios-arrow-right"></i>',
            '</div>'
        ].join(""),
        scope: {
            'items': '=',
            'value': '=ngModel'
        },
        link: function (scope, element, attrs, $filter) {
            //validations
            //if (typeof attrs.required != "undefined"){
            //    // a value is required, hence invalidate this control.
            //
            //}

            //Some specific logic here. 

            scope.validate = function () {
                // validation that kicks in when user chooses to close the modal. 
            };

            scope.$on('$destroy', function () {
                scope.modal.remove();
            });
        }
    }
}

Basically, this gives the user the ability to select several types of contacts from the modal dialog used in the ionic application.

I use this directive in my html (inside the form) as follows:

<multi-select
    name="contactTypes"
    items="contact_types"
    text="Contact types"
    header-text="Choose contact types"
    allow-empty="false"
    ng-model="contact.contact_types"
    ></multi-select>

Question: I'm not sure how to install ng-pristine, ng-needed ng-pristine classes if the user hasn't selected anything. Where will the code for managing custom validation work? What do I need to do so that I can use this directive like any other input control with an ng model?

+4
source share
1 answer

ng-model, ( " " ). :

  • ngModel:

    function multiSelect($ionicModal) {
        return {
            ...
            require: 'ngModel',
            ...
        };
    }
    
  • link ngModel $isEmpty. , undefined, '', null NaN. , , :

    link: function(scope, element, attrs, ngModel) {
        ...
        var originalIsEmpty = ngModel.$isEmpty;
    
        ngModel.$isEmpty = function(value) {
            return originalIsEmpty.call(ngModel, value) || value.length === 0;
        };
        ...
    }
    
  • , ng-required :

    <multi-select ... ng-required="true"></multi-select>
    

    Angular $isEmpty ng-invalid-required <multi-select>.

$pristine $untouched . , , ngModel:

  • , - , ngModel.$setTouched().
  • , "" - , , ngModel.$setDirty().

, ngModel link scope: { 'value': '=ngModel' }.

+1

Source: https://habr.com/ru/post/1606137/


All Articles