kuba
kuba

Reputation: 21

Angular directive with ngModelController formatter

I'm trying to implement a simple directive that adds a formatter to <input type="date"> field. The directive looks like:

myApp.directive("date-format", function (dateFilter) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, element, attributes, ngModelController) {
            ngModelController.$formatters.push(function (modelValue) {
                return modelValue && new Date(modelValue);
            });
        }
    };
});

It worked pretty well until I changed its name to mb-date-format. I created a JS fiddle: http://jsfiddle.net/HB7LU/4458/. It seems to work properly with names like aaa, bbb, ccc and so on, but it stops working when you change the name to jjj, zzz, ….

Upvotes: 2

Views: 128

Answers (2)

jonc.js
jonc.js

Reputation: 438

Looking over your fiddle I have found a couple of issues which may be the cause:

  1. You're using the date type on the input. The built in browser date selector apis are very difficult to override, thus your formatting solution won't work in many browsers.

Solution part one: Change your input type to text

<input type="text" ng-model="date" mb-date-format>

I understand this means that you may have to roll your own picker, but if you want customization, you will need to do that. If you don't mind dependencies, and your demands are not too many, AngularUI makes a pretty extensible datepicker.

  1. Your parser function is never getting hit, and you probably don't need a parser for the formatting here anyway.

Solution part two: Format the output in a formatter function I modified your fiddle here this also implements the directive name from your initial inquiry.

Upvotes: 0

PokeItWithAStick
PokeItWithAStick

Reputation: 316

Try camel casing the directive name to "dateFormat" eg :

myApp.directive("dateFormat", function (dateFilter) 


and then in the use it in the html like this

<input type="date" ng-model="date" date-format>

Upvotes: 2

Related Questions