angularjs 更改控制器之间共享的工厂对象 [英] angularjs changing factory object shared between controllers
问题描述
在工厂对象更新后,是否可以更新指向工厂对象的范围变量?如果有 2 个 angular 控制器共享一个工厂对象,如果其中一个控制器更改了工厂对象,则不会反映在另一个控制器的作用域变量中.
例如:http://jsfiddle.net/zjm0mo10/结果将是
"Factory foo.bar is 555" 而不是
工厂 foo.bar 是 666"var app = angular.module('myApp', []);app.factory('testFactory', function(){返回 {富:{酒吧:555},}});函数 HelloCtrl($scope, testFactory){$scope.bar = testFactory.foo.bar;$scope.clickme = function(){alert("testFactory.foo.bar"+testFactory.foo.bar);$scope.$apply();}}函数 GoodbyeCtrl($scope, testFactory){testFactory.foo.bar = 666;}<div ng-controller="HelloCtrl"><p>工厂 foo.bar 是 {{bar}}</p><button ng-click="clickme();">btn</button>
</html>
将范围属性设置为 testFactory.foo
,例如
$scope.foo = testFactory.foo;
和
Factory foo.bar 是 {{foo.bar}}</p>
这样,作用域属性将引用保持不变(不会被覆盖)的 testFactory.foo
.
此外,您需要从 clickme()
中删除 $scope.$apply()
.ng-click
已经触发了一个摘要循环.
http://jsfiddle.net/zjm0mo10/1/
Is it possible to update the scope variable that points to a factory object, after the factory object is updated? If there are 2 angular controllers which share a factory object, if one of the controllers changes the factory object, it is not reflected in the scope variable of the other controller.
Ex: http://jsfiddle.net/zjm0mo10/ The result will be
"Factory foo.bar is 555" instead of
"Factory foo.bar is 666"var app = angular.module('myApp', []);
app.factory('testFactory', function(){
return {
foo: {bar:555},
}
});
function HelloCtrl($scope, testFactory)
{
$scope.bar = testFactory.foo.bar;
$scope.clickme = function()
{
alert("testFactory.foo.bar "+testFactory.foo.bar);
$scope.$apply();
}
}
function GoodbyeCtrl($scope, testFactory)
{
testFactory.foo.bar = 666;
}
<html>
<div ng-controller="HelloCtrl">
<p>Factory foo.bar is {{bar}}</p>
<button ng-click="clickme();">btn</button>
</div>
</html>
Set your scope properties to testFactory.foo
, eg
$scope.foo = testFactory.foo;
and
<p>Factory foo.bar is {{foo.bar}}</p>
That way, the scoped property will reference testFactory.foo
which remains intact (not overwritten).
Also, you need to remove $scope.$apply()
from clickme()
. ng-click
already triggers a digest cycle.
http://jsfiddle.net/zjm0mo10/1/
这篇关于angularjs 更改控制器之间共享的工厂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!