user1506145
user1506145

Reputation: 5296

Sharing data with between Controllers with a Factory, AngularJS

I want to share data between controllers:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.factory('Data', function(){
    return {show: true, text: "Hello"};
});

myApp.controller('ctrl1', ['$scope', 'Data', function($scope, Data) {
    $scope.data = Data;
}]);

myApp.controller('ctrl2', ['$scope', 'Data', function($scope, Data) {
    $scope.click = function(){
      Data = {text:"Hello2", show:true};
    }
}]);
</script>
<body ng-app='myApp'>
<div style="background-color:red;margin-top:30px;" ng-controller="ctrl1">
    {{data.text}}
</div> 
<div style="background-color:yellow;margin-top:30px;" ng-click="click()" ng-controller="ctrl2">
    Click to change data
</div> 
</body>

Demo http://plnkr.co/edit/QHuWLYjBqDvl20fL7eeu?p=preview . This doesn't work, however if I write

Data.text = 'Hello2';
Data.show = true;

It works perfectly. Demo http://plnkr.co/edit/xKtLUlBu0dQPUsiNCRyC?p=preview

It would be very handy to just updating a model by just specifying Json, how can I do it?

Upvotes: 1

Views: 89

Answers (2)

red-X
red-X

Reputation: 5138

When you write

Data = {text:"Hello2", show:true};

You are overwriting the local Data variable with a new local object

When writing

Data.text = 'Hello2';
Data.show = true;

The original object that is also linked in parent scopes remains, you are overwriting variables inside the Data object instead of just overwriting the local Data link to the object

Upvotes: 1

dfsq
dfsq

Reputation: 193301

By doing Data = {text:"Hello2", show:true}; you completely overwrite initial Data object, which results into broken reference. That's why you can't just assign completely new object. You however can do it something like this:

myApp.factory('Data', function(){
    return {
        prop: {show: true, text: "Hello"}
    };
});

and later:

Data.prop = {text: "Hello2", show: true};

Upvotes: 1

Related Questions