如何在服务中定义数组并在 AngularJS 中的 2 个控制器之间共享它

How to define an array in a Service and share it between 2 controllers in AngularJS

本文关键字:控制器 共享 中的 之间 服务 定义 数组 AngularJS      更新时间:2023-09-26

>我有 2 个控制器 FirstController、SecondController 和一个服务,如下所示:

app.factory('Data', function(){
    return [];
});

我将该服务用于两个控制器,如下所示:

app.controller("FirstController", function($scope, $http, Data) { 
// getting an JSON array using $http.get() and storing it into Data.myArray for example
}
app.controller("SecondController", function($scope, $http, Data) { 
// I want to do something like this, to recover the array from the Service 
$scope.recoveredArray = Data.myArray;
// then do stuff to the reoveredArray...
}

最后将恢复的数组从第二控制器显示到 html 视图。

提前非常感谢你。

你的服务需要返回一个对象,例如属性 myArray。

app.factory('data', function() {
    return {
      myArray: []
    };
});

看到我为另一个SO问题所做的小提琴:https://jsfiddle.net/gkmtkxpm/1/