簡體   English   中英

如何在服務中定義數組並在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視圖的recoveryArray。

提前非常感謝您。

您的服務需要返回帶有屬性myArray的對象。

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

請參閱我對另一個SO問題所做的小提琴: https : //jsfiddle.net/gkmtkxpm/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM