重点是:我正在为 Web 应用程序构建图表。我从 Java 中的 Web 服务的单个对象获取图表信息。 这基本上是我正在检索的 JSON 对象的格式
{ "chart1Info": [9, 42, 43, 7, 20], "chart2Info": [45, 3, 21, 34] (...and so on)}
在我的 app.js (我的 AngularJS 代码所在的位置)上,我有 7 个用于 7 个图表的 Controller 。在每个 Controller 中,我调用服务来获取包含所有信息的同一对象。
app.controller('chart1', function($scope, $http){
$http.get('//WEBSERVICE_PATH').then(function(response) {
$scope.chartData = response.data; //The JSON object
//Then I build the charts...
});
});
我想要做的是仅调用服务一次并保存对象,以便我的 Controller 可以使用它,因为每个 Controller 都是相同的对象。 我尝试使用包含所有其他 Controller 的主 Controller ,并将 $rootScope 的属性设置为 JSON 对象,例如
$rootScope.chartData = response.data;
//Inside the $http.get() function
但它在其他 Controller 中未定义。 谢谢各位的解答
最佳答案
您需要在 Controller 中添加 $rootScope 依赖项,否则 $rootScope 将无法正常工作。
app.controller('chart1', function($scope, $http,$rootScope){
$http.get('//WEBSERVICE_PATH').then(function(response) {
$scope.chartData = response.data; //The JSON object
//Then I build the charts...
});
});
关于javascript - 如何在多个 Controller 中使用相同的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43846810/