简体   繁体   中英

Angularjs - sharing data between controllers

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'.

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';
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM