How to use datepicker in AngularJS using custom di

2019-05-21 00:32发布

问题:

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?

回答1:

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/



回答2:

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();
});