如何在AngularJS中使用日期选择器,使用自定义指令作为类

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

本文关键字:自定义 指令 日期 AngularJS 选择器      更新时间:2023-09-26

下面是我使用的HTML和Javascript代码。

HTML代码:

<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脚本:

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

现在,当我点击文本框时,日期选择器弹出窗口不会出现。

有人能帮我提供一个解决方案,让这个日期选择器工作吗?

我可以在您的代码中看到一些错误。您没有具体说明您使用的是哪个日期选择器,所以我认为它是jquery。基于标记的UI。

1) 您需要添加jquery。UI CSS也是

2) 您不能使用元素。日期选择器元件不是jQuery对象。您需要将其制作成jquery对象。像波纹管

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

这是一把正在工作的小提琴http://jsfiddle.net/esx6k1nc/

我不确定这是否与引导程序日期选择器的格式相同。这对我使用bootstrap日期选择器时很有效。将此添加到您的控制器:

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