1

There are two controllers. one controller will write data into an object & the other controller needs to read it. Can i have one global variable in my app.js file, that can be used in both the controllers. i am confused, why does one need to use service to share data between controllers? app.js::::::

var msg = 'message init'
app.controller('readController', function($scope){
      $scope.msg = msg
      console.log(msg)
});
app.controller('writeController', function(){
      msg = 'message is written'
});

Doesn't the change made in write controller get reflected into the read controller? in that case, the console must have 'message is written'.

2
  • This is a JavaScript question relating to closure and variable scope. You could make child controllers and update a variable in a parent controller, but this is not preferred practice. You may feel that its overkill to use a service to share one value but its not. Any data shared between controllers should be in a service. This makes it testable and injectable. Commented Nov 22, 2014 at 6:16
  • yeah, your code "works", but it undermine's the separations that angular makes it easy to enforce. you give up automated unit testing, there's no conflicting variable protection, both controllers execute slower than they would with DI, there's no inherent data change notification, no protection from minification errors, it's harder to debug, and well, need i list off more? that said, you can use $scope to share without a service. Commented Nov 22, 2014 at 6:34

2 Answers 2

1

You can read and write data from/to $rootScope. For simple data I do not think you'll need a service. Keep in mind however that this may not be a good design.

app.controller('readController', function($scope, $rootScope){
  $scope.myMsg = $rootScope.msg;
  console.log($scope.myMsg);
});

app.controller('writeController', function($rootScope){
  $rootScope.msg = 'message is written';
});
Sign up to request clarification or add additional context in comments.

Comments

0

I will not advice to write global variable and then share data between controller. Instead of that, you can share data with service and factory that's more simple.

Comments