kumareloaded
kumareloaded

Reputation: 3952

How to use datepicker in AngularJS using custom directive as a class?

Below are my HTML and Javascript code which I used.

HTML Code:

<html>
<head>
<script
    src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="date.js"></script>
</head>
<body>
    <div ng-app="app">
        <input type="text" ng-model="date" class="datepicker"></input>
        {{ date }}
    </div>
</body>
</html>

Java Script:

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

datePicker.directive('datepicker', function () {
    return {
        restrict: 'C',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'dd, MM, yy',
                onSelect: function (date) {
                    scope.date = date;
                    scope.$apply();
                }
            });
        }    
    };
});

Now when I click on the textbox, the datepicker popup is not coming.

Can someone please help me with a solution to make this datepicker work?

Upvotes: 3

Views: 21239

Answers (2)

Juan
Juan

Reputation: 1

I'm not sure if this is the same format for bootstrap-datepicker. This worked for me when using bootstrap-datepicker. Add this to your controller:

$('#datepicker').datepicker({
    todayHighlight: true,
    format: 'mm/dd/yyyy',
    autoclose: true
 }).on('changeDate', function (date) {
    $scope.date = date.format();
    $scope.$apply();
});

Upvotes: 0

Icepick
Icepick

Reputation: 156

I can see a few mistakes in your code. You have not specifically said which datepicker you are using so I assumed it was jquery.UI based on your tags.

1) you need to add jquery.UI CSS also

2) you can't use element.datepicker. element is not jQuery object. You need to make it into jquery object. like bellow

HTML:

<div ng-app="myApp"> <input type="text" ng-model="date" class="datepicker"></input> </div>

JS:

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


app.directive('datepicker', function () {
return {
    restrict: 'C',
    require: 'ngModel',
     link: function (scope, element, attrs, ngModelCtrl) {
            $(element).datepicker({
                dateFormat: 'dd, MM, yy',
                onSelect: function (date) {
                    scope.date = date;
                    scope.$apply();
                }
            });
        }    
    Y};
});

Here is a working fiddle http://jsfiddle.net/esx6k1nc/

Upvotes: 7

Related Questions