简体   繁体   English

AngularJS-在控制器之间共享数据

[英]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. 我可以在我的app.js文件中有一个全局变量,该变量可以在两个控制器中使用。 i am confused, why does one need to use service to share data between controllers? 我很困惑,为什么一个人需要使用服务在控制器之间共享数据? app.js:::::: 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. 您可以在$ 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. 取而代之的是,您可以更简单地与服务和工厂共享数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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