0

我有 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...

}

最后显示从 SecondController 到 html 视图的recoveredArray。

非常感谢您提前。

4

1 回答 1

1

您的服务需要返回一个具有例如属性 myArray 的对象。

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

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

于 2016-03-01T21:51:03.353 回答