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

时间:2016-03-01 21:46:21

标签: javascript angularjs data-binding angular-services angular-controller

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

}

并最终将SecondAtroller中的restoredArray显示到html视图。

非常感谢你。

1 个答案:

答案 0 :(得分:1)

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

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

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

相关问题