https://plnkr.co/edit/hccJqwtDlqcOBhxnwZ94?p=preview
在此示例中,当工厂返回值在$timeout
中更改时,指向工厂的范围变量(在这种情况下为anotherVar
)反映了更改,但指向特定属性的变量({ {1}})。
var
// Code goes here
angular.module("sample",[])
.controller("myctrl",function($scope,TestService){
$scope.var = TestService.name;
$scope.anotherVar = TestService;
})
.factory('TestService',function($timeout){
var ret = {};
ret.name = "temporary";
$timeout(function() {
ret.name = "final";
},4000);
return ret;
});
答案 0 :(得分:1)
您的第一个变量var
已根据第一个工厂调用的返回值进行设置。由于它的作用域是控制器myCtrl
,因此不会在其他地方寻找更改。
您的第二个变量anotherVar
的作用域是工厂,因此反映了$timeout()
中的更新。
您可以阅读有关AngularJS作用域here的更多信息。
答案 1 :(得分:0)
不是特定于angular的,而是使用javascript以及按引用传递或按值传递之间的差异(在几乎所有编程语言中都是已知的)。
分配变量时:
var a = 3;
//then
var b = a;
// here you'expecting that b == 3, isn't it?
// well you're right!
//now let's do the following:
b = 5;
// are you expecting to see 5 into a (because b=a)?
// well, a == 3
因为a变量是原始值,所以情感(b = a)是传递变量(=仅将a的变量设置为b)。
如果您现在尝试通过引用传递(使用对象):
var a = {}; // define a as an object
a.a = 3; // a get a property a and its value is 3
var b = a; // now the affectation is an object (=pass by reference)
// we are not assigning the value of a but its reference.
如果要更改b对象中的a属性: b.a = 5?
现在,如果您查看一个对象,您将看到a.a = 5
这就是您工厂行为举止的原因。
角工厂是对象。
您将返回对象 TestService
但是您的$scope.var
被分配了一个原始值(TestService.name
),因此当该值更改时,它不会反映在您的$scope.var
中。
在第二行中分配了一个对象(TestService
),因此如果对该对象内部的属性进行了赋值,则会被反映,因为它是 SAME OBJECT < / strong>。
总结: