How to use datepicker in AngularJS using custom di

2019-05-20 23:46发布

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?

2条回答
Luminary・发光体
2楼-- · 2019-05-21 00:22

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();
});
查看更多
smile是对你的礼貌
3楼-- · 2019-05-21 00:24

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/

查看更多
登录 后发表回答