如何在服务中定义数组并在 AngularJS 中的 2 个控制器之间共享它
How to define an array in a Service and share it between 2 controllers in AngularJS
我有 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 视图。
非常感谢您。
您的服务需要 return 一个对象,例如属性 myArray。
app.factory('data', function() {
return {
myArray: []
};
});
看到这个 fiddle 我为另一个 SO 问题做了:https://jsfiddle.net/gkmtkxpm/1/
我有 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 视图。
非常感谢您。
您的服务需要 return 一个对象,例如属性 myArray。
app.factory('data', function() {
return {
myArray: []
};
});
看到这个 fiddle 我为另一个 SO 问题做了:https://jsfiddle.net/gkmtkxpm/1/