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

[亡魂溺海] 提交于 2019-12-08 01:12:08

问题


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


来源:https://stackoverflow.com/questions/26798912/how-to-use-datepicker-in-angularjs-using-custom-directive-as-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!