Reputation: 437
I want to add two new select boxes (from and until) using ng-click and then add then update the users selection in my scope. I can add the select boxes but I'm having trouble binding the selects to my array.
My HTML:
<div ng-repeat="time in availability.times" class="calendar--availability--time">
<select ng-model="availability.times.time.from[$index]">
<option>...</option>
</select>
<select ng-model="availability.times.time.to[$index]">
<option>...</option>
</select>
</div>
<button class="button--secondary margin__top" ng-click="addNewTime()"><span>Add another slot</span></button>
My js/angular:
$scope.availability = {
times: [
time: {from: '09:00', to: '21:00'}
]
}
$scope.addNewTime = function() {
var newTime = {time: { from: '', until: ''}};
$scope.availability.times.push(newTime);
}
Upvotes: 0
Views: 54
Reputation: 4443
There were several issues in both your HTML markup and your JavaScript code.
The time
name does not belong inside the array brackets. You don't really seem to need the time
name, just from
and to
. So this:
times: [
time: {from: '09:00', to: '21:00'}
]
Should be this:
times: [
{from: '09:00', to: '21:00'}
]
Then you need to reflect this in your addNewTime
function and also correct the typo. Where you have:
var newTime = {time: { from: '', until: ''}};
It should be:
var newTime = {from: '', to: ''};
(Note that you had until
instead of to
).
For the ng-model
binding in your HTML, there is no need to reference the full model with the $index
variable. You just need the time
variable that is created by ng-repeat
. So instead of this:
<select ng-model="availability.times.time.from[$index]">
You should have this:
<select ng-model="time.from">
Here is a fiddle that shows it all working: http://jsfiddle.net/etnfwdw7/.
Finally, you should familiarize yourself with the developer tools built into most browsers. Some of these errors would have shown up in the developer console.
Upvotes: 1