您好,我在一个页面中有两个表单,一个用于以前数据的参考,一个是实际表单。所以我必须将相同的json(实际上来自数据库)分配给页面中的两个不同的表单。我在主窗体中更改选项值时出现问题,参考表格值也会发生变化。我想要的甚至是主要的表单更改值,引用表单应保留旧值。请检查我的代码。
https://jsfiddle.net/sanuman/kts7je89/24/
感谢您的任何帮助和建议。
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>
答案 0 :(得分: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。