Reputation: 3486
I'm trying to sync two drop downs in Angular 1.4.7 so that when one dropdown is updated the other is set to the same value, and vice-versa. Seems like im close but instead of being synced, the other drop down changes to the default "select" value.
This is a simplified version of an issue on a site im working on. The site in question is very data driven, so I'm hoping to get this to work within this structure. That is, an array of inputData objects that each contain array of months & a selectedMonth attribute.
The application works fine, except for this new requirement. What am I missing?
I included the source and a plunker showing the issue.
https://plnkr.co/edit/wSsBO4dHP0SR6HliP0b8?p=preview
HTML
<div class="form-group" ng-repeat="input in inputData">
<select name="inputMonth__{$index}}" id="inputMonth__ID_{{$index}}"
ng-model="input.selectedMonth"
ng-change="option_changed(input)"
ng-options="month as month for month in input.Months " >
<option value="" style="display:none">Select</option>
</select>
<br><br>
</div>
controller - test.js
'use strict';
var app = angular.module('app',[]);
app.controller('testController', ['$scope', function ($scope) {
$scope.inputData=[];
$scope.inputData.push(new inputData());
$scope.inputData.push(new inputData());
$scope.option_changed = function(Input) {
SyncDropdowns(Input)
};
function SyncDropdowns(selectedInput){
for(var i = 0; i < $scope.inputData.length ; i++) {
var currInput=$scope.inputData[i];
if (currInput!=selectedInput){
currInput.selectedMonth=$.extend({}, selectedInput.selectedMonth);
}
}
}
function inputData(){
this.selectedMonth={};
this.Months=["April", "May", "June", "July"];
}
}]);
Upvotes: 2
Views: 468
Reputation: 1282
Inside ng-repeat each instance gets its own scope. Try using $parent.input.selectedMonth
in ng-model
Upvotes: 0
Reputation: 4904
The jquery extend
$.extend({},"June")
returns
{
"0": "J",
"1": "u",
"2": "n",
"3": "e"
}
Update this function
function SyncDropdowns (selectedInput) {
for(var i = 0; i < $scope.inputData.length ; i++) {
var currInput=$scope.inputData[i];
if (currInput!=selectedInput){
currInput.selectedMonth=selectedInput.selectedMonth;
}
}
}
Upvotes: 0
Reputation: 9616
Not sure what you intend to do here with
currInput.selectedMonth=$.extend({}, selectedInput.selectedMonth);
I changed it to simply the following and it syncs up fine.
currInput.selectedMonth=selectedInput.selectedMonth;
Here is the working plnkr
Upvotes: 3