javascript - 如何在多个 Controller 中使用相同的数据?

标签 javascript angularjs json web-services

重点是:我正在为 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/

相关文章:

javascript - Socket.io 传递回调函数

javascript - 使用 html5 数据操作和 Angular

javascript - 如何隐藏自定义指令

javascript - 根据 JSON 更改图像的 src 属性

javascript - 如何通过JavaScript获取类名?

Javascript RegExp 非捕获组

javascript - AngularJS - ng-grid 和 data-ng-grid 之间的区别

json - Node : saving JSON to MongoDB

android - 如何在android中获取json数组值?

python - 将 Python 对象转换为 JSON 输出