我已经用 AngularJS 进行了几天的探索,我想创建一个日期选择器。我碰到了一些对我来说还不完全清楚的事情。起初,这是我为我的 datepicker 编写的代码:
angular.module('datepicker', []).directive('myDatepicker', function() {
return {
scope: {
clickCallback: '&',
options: '='
},
restrict: 'E',
templateUrl: 'datepicker.php',
link: function($scope, $element, $attr) {
$scope.day = 0;
$scope.month = 0;
$scope.year = 0;
$scope.years = [];
$scope.days = [];
$scope.months = getStandardMonths();
$scope.init = function() {
for (var i = 1; i <= 31; i++)
$scope.days.push({
value: i,
text: (i < 10) ? "0" + i : i
});
$scope.days.unshift({
value: 0,
text: "--"
});
$scope.months.unshift({
value: 0,
text: "--"
});
var year = new Date().getFullYear();
var start = year + 3;
var end = year - 50;
for (var j = start; j >= end; j--) {
$scope.years.push({
value: j,
text: j
});
}
$scope.years.unshift({
value: 0,
text: "--"
});
}
$scope.update = function() {
var last = 32 - new Date($scope.year, $scope.month - 1, 32).getDate();
if ($scope.day > last) {
$scope.day = last;
}
last++;
if ($scope.days.length > last) {
var shrink = $scope.days.length - last;
$scope.days.splice(last, shrink);
} else {
for (var i = $scope.days.length; i < last; i++)
$scope.days.push({
value: i,
text: i
});
}
if ($attr.partial) {
$scope.dism = !($scope.year);
$scope.disd = !($scope.month);
if (!$scope.year) {
$scope.disd = true;
$scope.day = $scope.month = 0;
}
if (!$scope.month) {
$scope.day = 0;
}
}
}
$scope.disd = $scope.dism = ($attr.partial === undefined) ? false : $attr.partial;
$scope.init();
}
};
});
这是我为渲染 datepicker 模块而编写的模板:
<select ng-model="day" ng-options="d.value as d.text for d in days" ng-visible="!disd"> </select>
<select ng-model="month" ng-options="m.value as m.text for m in months" ng-change="update()" ng-visible="!dism"></select>
<select ng-model="year" ng-options="y.value as y.text for y in years" ng-change="update()"></select>
我的用法相当简单:
<my-datepicker partial="true" />
现在,当我多次复制上面的行时,它仍然呈现一个日期选择器控件(html 页面上没有显示多个日期选择器)。我似乎无法理解为什么,如果有人可以在这里阐明一些观点,我将非常感激。
我有一个不同项目的列表,所有项目都有自己的日期。我的下一步是将列表对象中的日期绑定到该日期选择器内的函数。
注意:部分属性是允许用户不填写完整的日期而只填写年份或年份和月份。