gpt4 book ai didi

javascript - AngularJS 监视工厂对象的属性 - 意外行为

转载 作者:行者123 更新时间:2023-11-30 11:35:59 25 4
gpt4 key购买 nike

我想了解 AngularJS 在观察工厂提供的对象变化时的某种行为。

根据我是在 Controller 中还是在 html 中读取工厂提供的对象的属性,会有不同的行为。

比较以下两种在 View 中显示属性的方式:

app.controller("testController", function($scope, testFactory){
$scope.test_obj = testFactory.read();
$scope.test_prop = testFactory.read().prop;
});

<div>{{test_obj.prop}}</div>
<div>{{test_prop}}</div>

当 testFactory 中的属性更改时,更改仅在第一种情况下在 View 中更新,当整个对象被声明到作用域并在 View 中调用该属性时。当属性直接声明到范围时,它不会在 View 中自动更新。

可以在以下 jsfiddle 中观察到此行为:https://jsfiddle.net/fb86p4fm/

这种行为的原因是什么?

最佳答案

$scope.test_prop = testFactory.read().prop;

在上面这行中,prop 的初始值为 0。在 javascript 中,数字是按值复制的,而对象/数组是按引用复制的。 $scope.test_obj 引用服务对象,而 $scope.test_prop 不是。

关于javascript - AngularJS 监视工厂对象的属性 - 意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44396711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com