Search code examples
angularjsangularjs-directiveangular-ui-bootstrapangular-ui-datepicker

Extend Angular-UI Datepicker directive


I have been using the ui-datepicker from Angular-ui-bootstrap a lot, but every time I use it, I need to set it up, the same way I do every time. So I was wondering if I could create a directive called custom-datepicker I could use like

<custom-datapicker>

So that I can set the settings in the directive once, and then reuse it everywhere on my site.

I tried to create a directive like this one below

app.directive('customDatapicker', function () {
    return {
        restrict: 'E',
        require: 'ngModel',
        templateUrl: function (elem, attrs) {
            return '/AngularJS/Directives/customDatapicker.html'
        },
        link: function (scope, element, attrs, ngModel) {
        $scope.inlineOptions = {
            showWeeks: true
        };

        $scope.dateOptions = {
            formatYear: 'yy',
            startingDay: 1
        };


        $scope.open = function () {
            $scope.opened = true;
        };

        $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
        $scope.format = $scope.formats[0];

        $scope.selected = {
            opened: false
        };

        },
});

I am also trying to use a template, so that i can do some custom html wrapper around it. So far I have got nothing besides the sample html from

TemplateHTML

<p class="input-group">
        <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="ngModel" is-open="selected.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" />
        <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open()"><i class="glyphicon glyphicon-calendar"></i></button>
        </span>
    </p>

In the Template html I'm trying to make the binding between my directive's input model in the datepicker's ng-model by doing ng-mode='ngModel', which i don't think is the right way.

I use my directive in my html page like this, where data is a JS Date Object

<custom-datapicker ng-model='data'>

Can this be done?


Solution

  • Instead of using ng-model on your custom directive, define a custom attribute, then pass that value into the ng-model attribute of the datepicker.

    <custom-datepicker customAttrib="val" ...
    

    Then in the template:

    <input ng-model="{{customAttrib}}" ...