subhra subhra - 2 months ago 9
AngularJS Question

Getting issue while dynamically setting value in drop down list using Angular.js

I am getting an issue. I have two drop down list with same value. But when i am setting any value to first drop down list,the second one is taking that one. I am explaining my code below.

<div class="col-md-6">
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Day Form :</span>
<select class="form-control" id="daysFrom" ng-model="daysFrom" ng-options="qua.name for qua in listOfDays track by qua.value ">
</select>
</div>
</div>
<div class="col-md-6">
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Day To :</span>
<select class="form-control" id="daysTo" ng-model="daysTo" ng-options="qu.name for qu in listOfDays track by qu.value ">
</select>
</div>
</div>


Here i have two drop down menu and suppose i am setting the value to first one like below.

$scope.daysFrom.value=2;

$scope.listOfDays=[{
name:'Select Day',
value:''
}]
$scope.daysFrom=$scope.listOfDays[0];
$scope.daysTo=$scope.listOfDays[0];
$http({
method:'GET',
url:"php/customerInfo.php?action=day",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
angular.forEach(response.data,function(obj){
var data={'name':obj.day_name,'value':obj.day_id};
$scope.listOfDays.push(data);

})
},function errorCallback(response) {
})


The second one is also taking the same value which should not happen. I need to set different value to both drop down list. Please help me.

Answer

Both $scope.daysFrom and $scope.daysTo are references to the same object $scope.listOfDays[0]. Changes to any of this objects will be reflected in all of them.

To fix this, you can use angular.copy. Here is an example:

$scope.daysFrom = angular.copy($scope.listOfDays[0]);
$scope.daysTo = angular.copy($scope.listOfDays[0]);