0

我创建了一个 rootScope 变量,例如

$rootScope.globalData = data;
$rootScope.globalData.chillerConditions.HeatSource.Value = "ST";    //Default Value
$scope.chillerConditions.HeatSource.Value = 1;                      //Default Value

data我从 api 的返回值在哪里。还要创建一个范围变量,它是一个包含项目列表的对象。

$scope.chillerAttributes = data.ObjCandidateListChillerAttributes;
$scope.chillerConditions = data.ObjCandidateListConditions;

在 HTML 上,我有:

<select ng-model="chillerConditions.HeatSource.Value" style="width:53%;" ng-options="item.Id as item.Description for item in ValidRatingHeatSource" ng-change="heatSourceChanged()" id="ddRatingHeatSource" class="form-control search-select designComboboxHeight" data-container="body"></select>

这里ValidRatingHeatSource

$scope.ValidRatingHeatSource = \*list of items*\

在更改下拉菜单时,我编写了一个函数。在那里面

if($scope.chillerConditions.HeatSource.Value == 2)
{
  $rootScope.globalData.chillerConditions.HeatSource.Value = "HW";
}
else
{
  $rootScope.globalData.chillerConditions.HeatSource.Value = "ST";
}

到现在为止是我当前的代码。问题是:

当调用上述函数时,只要当前$rootScope变量 ie$rootScope.globalData.chillerConditions.HeatSource.Value更改为"HW"or"ST"它也更改$scope.chillerConditions.HeatSource.Value"HW"or "ST"

为什么这样?

angularjs中是否有任何内置功能?请建议我是否犯了任何错误?也欢迎新的建议。

4

2 回答 2

2

这种行为是 JavaScript 的工作方式,与 AngularJS 无关。JavaScript 是一种面向对象(基于原型)的语言,其中对象通过引用而不是值来寻址。例如,将 car2 分配给 car1,它们都将引用同一个对象(JSFiddle

var car1 = {make: "Audi"}
var car2 = car1;
car2.make = "Toyota";

所以在你的情况下,$rootScope.globalData.chillerConditions.HeatSource$scope.chillerConditions.HeatSource是同一个对象。

相反,您似乎想创建一个副本。你可以用angular.Copy做到这一点

$scope.chillerAttributes = angular.copy(data.ObjCandidateListChillerAttributes);
$scope.chillerConditions = angular.copy(data.ObjCandidateListConditions);
于 2014-12-29T12:56:21.240 回答
1

在您的示例中,您同时拥有 ng-model 和 ng-change,因此: 1. 用户在选择中更改值。2. $scope.chillerConditions.HeatSource.Value 变化 (ng-model) 3. heatSourceChanged 开始 (ng-change) -> $rootScope.globalData.chillerConditions.HeatSource.Value 变化

所以一切正常......

于 2014-12-29T12:34:59.087 回答