2016-11-13 38 views
0

您好,我有一個頁面中的兩個表單用於引用以前的數據,一個是實際的表單。所以我必須將相同的json(實際上來自數據庫)分配給頁面中的兩種不同的表單。當我在主窗體中更改選項值時,我遇到問題,參考窗體的值也會發生變化。我想要的甚至是主要的形式變化值,參考形式應該保留舊的價值。請檢查我的代碼。 https://jsfiddle.net/sanuman/kts7je89/24/
感謝您的任何幫助和建議。AngularJs將Json值分配給多個範圍

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; 
 
\t $scope.wspVdcMuniTbls = $scope.service_data; 
 
\t $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"> 
 
\t <select \t 
 
     ng-model="wspVdcMuniTblRef.tbl_vdc_municipality_id" 
 
\t options="municipalities_ref" 
 
\t ng-options="municipality_ref.id as municipality_ref.VDC_Muni_Name_Eng for municipality_ref in municipalities_ref"> 
 
\t </select> 
 
    </div> 
 

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

回答

1

你已經如預期所提供的工作的例子。問題是,既$scope.municipalities$scope.municipalities_ref指向同一個對象(同爲$scope.wspVdcMuniTbls$scope.wspVdcMuniTblsRef)時,這個賦值是由:

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

您應該創建的$scope.muni副本和「$ scope.service_data」是這樣的:

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

angular.copy(source, [destination]);的文檔可以找到there

+0

謝謝你的工作 https://jsfiddle.net/sanuman/kts7je89/25/ – sanu