1

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?

2
  • I'm afraid you linked same plnkr in both cases Commented Oct 6, 2014 at 13:50
  • @maurycy Sorry, Fixed now I think Commented Oct 6, 2014 at 13:53

2 Answers 2

1

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}; 
Sign up to request clarification or add additional context in comments.

3 Comments

Great thought, but it seems that doesn't work either plnkr.co/edit/gYChWzfQ2DkwKCOuL5Zw?p=preview
plnkr.co/edit/ZH2UKazOzogeFrJVZdLp?p=preview By writing $scope.data = Data.prop; you once again detach $scope.data from Data.prop. It should be however $scope.data = Data.
Yes, can be tricky sometimes. Read about Angular dot rule for more details on this.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.