gpt4 book ai didi

javascript - 在两个 Controller 之间共享数据angularjs

转载 作者:行者123 更新时间:2023-12-01 03:26:36 27 4
gpt4 key购买 nike

我似乎面临着在 angularjs 中的 Controller 之间共享数据的问题我有两个 HTML 文件,每个文件一个 Controller ,一个共享信息的服务和一个用于路由的常规应用程序文件。

这是第一个文件

<div class="container">
<button ng-click="broadcastData()"> Send </button> </div>

这是它相应的 Controller :

angular.module('myApp').controller('sendInfoController',
['$scope','$rootScope','$location'
function ($scope,$rootScope, $location)
{
$scope.broadcastData=function()
{
shareInfoService.sendData({info: "Okay"});
$location.path('/infoView');
}
}]);

这是第二个 HTML 文件:(infoView.html)

<div>
{{data}}
</div>

这是它相应的 Controller :

angular.module('myApp').controller('infoController',
['$scope','$rootScope',
function ($scope,$rootScope)
{
$scope.data="hello";
$rootScope.$on('sendTheData', function(event,args)
{
console.log(args);
$scope.data=args.info;
});
console.log($scope.data);
}]);

这是共享信息的服务:

angular.module('prkApp').factory('shareInfoService',
['$rootScope',
function ($rootScope) {

//Return the particular function
return ({
sendData: sendData
});

function sendData(data)
{
$rootScope.$broadcast('sendTheData', data);
};
}]);

当我单击第一个 HTML 文件中的按钮时,位置将更改为 infoView 并调用 shareInfoService.broadcastData 函数。

它重定向到第二个 HTML 文件。然而,该页面显示的信息是“hello”而不是“Okay”。

Web 控制台日志显示 {信息:“好的”}首先,然后立即说“你好”。

如何修正才能显示上一个 Controller 发送的数据?

最佳答案

您在更改位置之前发送广播,因此在广播事件时不会加载 infoController 中的监听器。您可以将值存储在服务中,然后让 infoController 在加载时检索它,而不是广播。

服务

angular.module('prkApp').factory('shareInfoService', ['$rootScope', function($rootScope) {
var data;

//Return the particular function
return ({
sendData: sendData,
getData: getData
});

function sendData(new_data) {
data = new_data;
};

function getData() {
return data;
}
}
]);

Controller

angular.module('myApp').controller('infoController', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.data = "hello";
console.log($scope.data);
$scope.data = shareInfoService.getData();
console.log($scope.data);
}
]);

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

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