javascript 如何使用自定义指令作为类在 AngularJS 中使用日期选择器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26798912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use datepicker in AngularJS using custom directive as a class?
提问by kumareloaded
Below are my HTML and Javascript code which I used.
下面是我使用的 HTML 和 Javascript 代码。
HTML Code:
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 Script:
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();
}
});
}
};
});
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?
有人可以帮我解决一个使这个日期选择器工作的解决方案吗?
回答by Icepick
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.
我可以在您的代码中看到一些错误。您没有具体说明您使用的是哪个日期选择器,所以我假设它是基于您的标签的 jquery.UI。
1) you need to add jquery.UI CSS also
1) 你还需要添加 jquery.UI CSS
2) you can't use element.datepicker. elementis not jQuery object. You need to make it into jquery object. like bellow
2)你不能使用element.datepicker。元素不是 jQuery 对象。你需要把它变成 jquery 对象。像下面这样
HTML:
HTML:
<div ng-app="myApp">
<input type="text" ng-model="date" class="datepicker"></input>
</div>
<div ng-app="myApp">
<input type="text" ng-model="date" class="datepicker"></input>
</div>
JS:
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/
这是一个工作小提琴http://jsfiddle.net/esx6k1nc/
回答by Juan
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:
我不确定这是否与 bootstrap-datepicker 的格式相同。这在使用 bootstrap-datepicker 时对我有用。将此添加到您的控制器:
$('#datepicker').datepicker({
todayHighlight: true,
format: 'mm/dd/yyyy',
autoclose: true
}).on('changeDate', function (date) {
$scope.date = date.format();
$scope.$apply();
});