gpt4 book ai didi

javascript - Angularjs - 在 Controller 之间共享数据

转载 作者:行者123 更新时间:2023-11-28 00:48:35 25 4
gpt4 key购买 nike

有两个 Controller 。一个 Controller 将数据写入对象,另一个 Controller 需要读取它。我的 app.js 文件中是否可以有一个全局变量,可以在两个 Controller 中使用。我很困惑,为什么需要使用服务在 Controller 之间共享数据?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'
});

写入 Controller 中所做的更改不会反射(reflect)到读取 Controller 中吗?在这种情况下,控制台必须显示“消息已写入”。

最佳答案

您可以从 $rootScope 读取数据或向 $rootScope 写入数据。对于简单的数据,我认为您不需要服务。但请记住,这可能不是一个好的设计。

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

app.controller('writeController', function($rootScope){
$rootScope.msg = 'message is written';
});

关于javascript - Angularjs - 在 Controller 之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27074618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com