sanu sanu - 27 days ago 6
AngularJS Question

AngularJs Assign Json value to multiple scope

Hi I have two form in one page one for reference of previous data and one is a actual form. So i have to assign same json(which actually are come from database) to two different form in a page. I have a problem when I change the option value in main form the reference form value also change. What I want is even the main form change value, reference form should retain old value. please check my code.
https://jsfiddle.net/sanuman/kts7je89/24/

thank you for your any help and suggestions.



var app = angular.module('myApp',[])
.controller('MyCtrl', function($scope, $http) {

$scope.muni=[
{
"id": 24001,
"VDC_Muni_Code": "24001",
"VDC_Muni_Name_Eng": "Anaikot",
"tbl_district_id": 24
},
{
"id": 24002,
"VDC_Muni_Code": "24002",
"VDC_Muni_Name_Eng": "Baldthali",
"tbl_district_id": 24
},
{
"id": 24003,
"VDC_Muni_Code": "24003",
"VDC_Muni_Name_Eng": "Balting",
"tbl_district_id": 24
},
{
"id": 24004,
"VDC_Muni_Code": "24004",
"VDC_Muni_Name_Eng": "Baluwapati",
"tbl_district_id": 24
}
];
$scope.service_data=[
{
"tbl_vdc_municipality_id": 24001
},
{
"tbl_vdc_municipality_id": 24004
},
{
"tbl_vdc_municipality_id": 24002
},
{
"tbl_vdc_municipality_id": 24003
}

];
$scope.municipalities_ref = $scope.muni;
$scope.municipalities = $scope.muni;
$scope.wspVdcMuniTbls = $scope.service_data;
$scope.wspVdcMuniTblsRef = $scope.service_data;
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<h2>
Main Form
</h2>
<div ng-repeat="wspVdcMuniTblRef in wspVdcMuniTblsRef">
<select
ng-model="wspVdcMuniTblRef.tbl_vdc_municipality_id"
options="municipalities_ref"
ng-options="municipality_ref.id as municipality_ref.VDC_Muni_Name_Eng for municipality_ref in municipalities_ref">
</select>
</div>

<h2>
Reference Form
</h2>

<div ng-repeat="wspVdcMuniTbl in wspVdcMuniTbls">
<select
ng-model="wspVdcMuniTbl.tbl_vdc_municipality_id"
options="municipalities"
ng-options="municipality.id as municipality.VDC_Muni_Name_Eng for municipality in municipalities">
</select>
</div>
</div>
</div>




Answer

The example you've provided work as expected. The thing is that both $scope.municipalities and $scope.municipalities_ref points to the same object (same for $scope.wspVdcMuniTbls and $scope.wspVdcMuniTblsRef) when this assigment is made:

$scope.municipalities = $scope.muni;
$scope.municipalities_ref = $scope.muni;
$scope.wspVdcMuniTbls = $scope.service_data;
$scope.wspVdcMuniTblsRef = $scope.service_data;

You should create a copy of $scope.muni and '$scope.service_data' like this:

$scope.municipalities_ref = angular.copy($scope.muni);
$scope.wspVdcMuniTblsRef = angular.copy($scope.service_data);

The documentation of angular.copy(source, [destination]); can be find there.