angularjs改变工厂对象控制器之间可共享 [英] angularjs changing factory object shared between controllers

查看:263
本文介绍了angularjs改变工厂对象控制器之间可共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能更新指向工厂对象的范围变量,工厂对象被更新后?
如果有2个共用一个工厂对象角控制器,如果所述控制器中的一个改变了工厂对象,它不反映在其他控制器的范围可变。


例如: http://jsfiddle.net/zjm0mo10/
其结果将是

工厂foo.bar是555,而不是


工厂foo.bar是666

  VAR应用= angular.module('对myApp',[]);
app.factory('TestFactory中',函数(){
返回{
    富:{条:555},
}
});功能HelloCtrl($范围,TestFactory中)
{
    $ scope.bar = testFactory.foo.bar;
    $ scope.clickme =功能()
    {
        警报(testFactory.foo.bar​​+ testFactory.foo.bar);
        $ $范围适用于()。
    }
}功能GoodbyeCtrl($范围,TestFactory中)
{
    testFactory.foo.bar = 666;
}< HTML和GT;
< D​​IV NG控制器=HelloCtrl>
    &所述p为H.;工厂foo.bar是{{酒吧}}&下; / P>
    <按钮NG点击=clickme();>&BTN LT; /按钮>
< / DIV>
< / HTML>


解决方案

设置范围属性 testFactory.foo ,例如:

  $ scope.foo = testFactory.foo;

 < P>工厂foo.bar是{{foo.bar}}< / P>

这样,作用域属性将引用 testFactory.foo 这仍然完好无损(未覆盖)。

此外,您还需要删除 $范围。$适用() clickme() NG-点击已触发消化周期。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆