问题
When I am using the angular ui datepicker within an ng-repeat block, the datepicker works correctly only for the first block. For the remaining repeated blocks, although the calender is displayed, a date cannot be selected.
Can someone please tell me how I could get it working? I tried to append the model name with a $parent but that didnt help.
I have a list of products and for each product there is a new release form which has two date fields. I am using ng-repeat to display the products and on clicking add a release, a release form for that product block is populated. The form is similar to
<form data-ng-submit="addRelease(b)">
<div class="form-field-container">
<label for="from">From</label>
<input class="datePicker" data-date-format="yyyy-mm-dd" type="text"
placeholder="yyyy-mm-dd" data-ng-model="from" id="from" required>
<br/>
<label for="to">To</label>
<input class="datePicker" data-date-format="yyyy-mm-dd" type="text"
placeholder="yyyy-mm-dd" data-ng-model="to" id="to" required>
<br/>
<label for="releaseNo">Release No.</label>
<input type="text" id="releaseNo" required>
<input class="btn btn-primary" type="submit" value="Add">
</div>
</form>
It works only for the product which is first in the list. For the other products although the dateui picker pops up but we cannot select a date.
回答1:
You need to supply each instance of the datepicker with a unique variable for the is-open and ng-model attributes. It's also best to provide a unique id for each. I make use of the $index variable that Angular provides in ng-repeat blocks.
See working plunker: http://plnkr.co/edit/HlD4pKJyamXGPM2UtL98?p=preview
Markup:
<div ng-repeat="item in items">
<input type="text" datepicker-popup="MM/dd/yyyy" ng-model="dt" is-open="opened[$index]" min="minDate" max="'2025-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" />
<button class="btn" ng-click="open($index)"><i class="icon-calendar"></i>
</button>
</div>
In your controller:
$scope.opened = [];
$scope.open = function(index) {
$timeout(function() {
$scope.opened[index] = true;
});
};
回答2:
The problem is that datepicker id's are duplicated. You can solve this by avoiding using ids at all, or generating them, for example by using $index.
<form data-ng-submit="addRelease(b)"><div class="form-field-container">
<label for="from-{{$index}}">From</label>
<input class="datePicker" data-date-format="yyyy-mm-dd" type="text"
placeholder="yyyy-mm-dd" data-ng-model="from" id="from-{{$index}}" required>
<br/>
<label for="to-{{$index}}">To</label>
<input class="datePicker" data-date-format="yyyy-mm-dd" type="text"
placeholder="yyyy-mm-dd" data-ng-model="to" id="to-{{$index}}" required>
<br/>
<label for="releaseNo">Release No.</label>
<input type="text" id="releaseNo" required>
<input class="btn btn-primary" type="submit" value="Add"></div></form>
来源:https://stackoverflow.com/questions/14099267/angular-ui-datepicker-in-ng-repeat-works-only-for-first-block