rootScope 正在更新范围变量更新



>我创建了一个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可变,即 $rootScope.globalData.chillerConditions.HeatSource.Value更改为"HW""ST"它也$scope.chillerConditions.HeatSource.Value更改为"HW""ST"

为什么会这样?

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

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

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

所以在你的例子中,$rootScope.globalData.chillerConditions.HeatSource$scope.chillerConditions.HeatSource是同一个对象。

相反,您似乎想要创建一个副本。你可以用角度来做到这一点。复制

$scope.chillerAttributes = angular.copy(data.ObjCandidateListChillerAttributes);
$scope.chillerConditions = angular.copy(data.ObjCandidateListConditions);

在你的例子中,你同时有ng-model和ng-change,所以:1. 用户在选择中更改值。2. $scope.冷却器条件.热源.值变化(ng模型)3. 热源更改开始 (ng-change) -> $rootScope.globalData.chillerConditions.HeatSource.值更改

所以一切都按预期工作...

最新更新