gpt4 book ai didi

javascript - 动态添加 Angular UI 日期选择器

转载 作者:行者123 更新时间:2023-11-30 08:35:18 24 4
gpt4 key购买 nike

在我的项目中,我需要向页面添加动态数量的日期选择器。我试过这样做(Plunker):

脚本:

var app = angular.module('plunker', ['ui.bootstrap']);    
app.controller('MainCtrl', function($scope) {
$scope.openDatePicker = function($event) {
$event.preventDefault();
$event.stopPropagation();

$scope.opened = true;
};

$scope.dateOptions = {
formatYear: "yy",
startingDay: 1,
format: "shortDate"
};

$scope.details = [{
"parameterValue": "2015-08-12"
}, {
"parameterValue": "2015-08-12"
}, {
"parameterValue": "2015-08-12"
}, {
"parameterValue": "2015-08-12"
}];
});

HTML:

<!DOCTYPE html>
<html ng-app="plunker">

<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="script.js"></script>
</head>

<body>
<div ng-controller="MainCtrl">
<form name="detailsForm" novalidate ng-submit="submitForm(detailsForm.$valid)">
<div ng-repeat="item in details" class="input-group">
<input ng-model="item.parameterValue" type="text" class="form-control" id="datePickerItem" datepicker-popup="shortDate"
is-open="opened" datepicker-options="dateOptions" current-text="Today" clear-text="Clear" close-text="Close" ng-readonly="false" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
</form>
</div>
</body>
</html>

问题是,当我尝试打开一个日期选择器时,所有的日期选择器都被打开(逻辑上,因为它们共享相同的 $scope.opened 变量)。此外,当我关闭它们并尝试再次打开它们时,什么也没有发生。

是否有一种优雅的方式来实现这一目标?

谢谢。

最佳答案

您所有的日期选择器都有 id="datePickerItem"

id 属性必须在 html 中是唯一的。试试这个:

id="datePickerItem_{{$index}}"

这会将 ng-repeat 的当前索引添加到 id,因此您可以相对确定您的 id 是唯一的。这也应该可以防止所有日期选择器同时打开。

此外,您正在为所有日期选择器使用同一个 opened 变量。

试试这个:

<div ng-repeat="item in details" class="input-group">
<input ng-model="item.parameterValue" type="text" class="form-control"
id="datePickerItem_{{$index}}" datepicker-popup="shortDate"
is-open="opened[$index]" datepicker-options="dateOptions" current-text="Today"
clear-text="Clear" close-text="Close" ng-readonly="false" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event, $index)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</div>

和:

$scope.opened = [];
$scope.openDatePicker = function($event, index) {
$event.preventDefault();
$event.stopPropagation();

$scope.opened[index] = true;
};

只需确保将 $scope.opened[index] 设置为 false,以防您关闭日期选择器。

关于javascript - 动态添加 Angular UI 日期选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31959002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com