angularjs changing factory object shared between controllers

馋奶兔 提交于 2019-12-11 12:49:03

问题


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>

回答1:


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/



来源:https://stackoverflow.com/questions/33642625/angularjs-changing-factory-object-shared-between-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!