Create Directive Attribute for Date Month/Year in Angular JS

Asked

Viewed 265 times

0

How to create a date formatting Month/A

I developed as code below, and it is not going through the console menus, IE, is not entering the link:

Note: there is no error in the console.

<div class="form-group">
                            <label class="control-label">Faz aniversário entre (Mês/Ano)</label>
                            <div class="row">
                                <div class=" col-sm-7">
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="material-icons">today</i></span>
                                        <input class="form-control" ng-model="state.filtro.dataInicialAniversario" placeholder="de" formatDateMesAno />
                                    </div>
                                </div>
                                <div class="col-sm-5">
                                    <input class="form-control" ng-model="state.filtro.dataFinalAniversario" placeholder="até" formatDateMesAno />
                                </div>
                            </div>
                        </div>

angular.module("app").directive('formatDateMesAno', directiveFormatMesAno);

    function directiveFormatMesAno() {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, elem, attr, modelCtrl) {

                console.log(scope);
                console.log(elem);
                console.log(attr);
                console.log(modelCtrl);
            }
        };

2 answers

1


In angular the name of the Directives are standardised by Camelcase, that is, when defining the name formatDateMesAno, in the HTML should be defined as format-date-mes-ano, until why the HTML is insensitive to upper and lower case.

Formatting the date

var myApp = angular.module('myApp', []);

myApp.controller("testectrl", function($scope){
 
})
.directive('mask', ['$timeout', 'maskService', function($timeout, maskService) {
   return {
     require: 'ngModel',
     scope: {
        mask: "@"
     },
     link: function(scope, element, attrs, ctrl) {
         var execute = function () {
             scope.$apply(function () {
                 ctrl.$setViewValue(maskService.maskNumber(ctrl.$modelValue, scope.mask));
                 ctrl.$render();
             });
         };
         element.bind('keyup', function () {
             execute();
         });
         
         $timeout(function () { 
             execute();
         }, 100);
      }
   };
}])
.factory("maskService", [function () {
    var _otherCharacters = /[^0-9A-Za-z]/g;

    var _applyMask = function (string, mask) {
        var formatedString = "";
        var startAt = 0;
        var sectors = mask.split(/[\(\)\.\-\/\s]/g);
        var sectorsSize = 0;
        var separators = mask.replace(/[^\(\)\.\-\/\s]/g, "").split("");
        for (var i = 0; i < sectors.length; i++) {
            formatedString += string.substring(startAt, startAt + sectors[i].length);
            sectorsSize += sectors[i].length;
            if (string.length < sectorsSize + 1) return formatedString;
            if (i < sectors.length - 1) formatedString += separators[i];
            startAt += sectors[i].length;
        }
        return formatedString;
    }
    
    var _removeCharacters = function (string) {
        return string.replace(_otherCharacters, '');
    };

    var _maskNumber = function (string, mask) {
        if (!string) return string;
        return _applyMask(_removeCharacters(string), mask);
    };
    
    return {
        maskNumber: _maskNumber
    };
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form name="gravaDados" ng-app="myApp" ng-controller="testectrl">

<input ng-model="data1" placeholder="dd" mask="XX">
<input ng-model="data2" placeholder="dd/mm" mask="XX/XX">
<input ng-model="data3" placeholder="dd/mm/yyyy" mask="XX/XX/XXXX">
  
</form>

  • That’s right, I didn’t mind when I used the copy and glue.. Could help me, what would be the best way to create a directive to format a month year date ?

  • i particularly always used ready-made solutions, but I will edit the answer with something specific for dates.

0

I don’t know if you’re the best way, but I managed to solve my problem this way.

.directive('formatDateMesAno', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {

            },
            link: function (scope, elem, attr, modelCtrl) {
                $(elem).mask('99/9999');
            }
        };
    });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.