我知道这已被多次询问,我试图与多个控制器共享动态数据。
分享静态数据工作正常,当我添加$http
时,我迷失了方向。
以下是我尝试实施类似方法的演示。
Demo正在基于静态数组工作,我已经指定了github端点,它提供了类似的数据。如何使这个演示基于动态数据。
```
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
return { filtercards: 'Default Data' };
});
myApp.factory('DynamicData', function ($q, $http) {
var dynamicdataObj = {};
dynamicdataObj.getDynamicData = function(type){
var url = 'https://api.github.com/users/tomalex0/repos'
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
};
//dynamicdataObj.lists = dynamicdataObj.getDynamicData('GOOG')
dynamicdataObj.lists = [{
id : 1,
name : 'First',
watchers_count :5
},{
id : 2,
name : 'Second'
}];
return dynamicdataObj;
});
function FirstCtrl($scope, Data, DynamicData) {
$scope.data = Data;
$scope.lists = DynamicData.lists;
$scope.toggleLike = function(item){
item.watchers_count = (item.watchers_count) ? (item.watchers_count+1) : 1;
}
}
function SecondCtrl($scope, Data, DynamicData) {
$scope.data = Data;
$scope.lists = DynamicData.lists;
}
```
答案 0 :(得分:1)
要保持数组同步,只需使用您的响应更新数组,而不会破坏引用并重新分配数组
myApp.factory('DynamicData', function ($q, $http) {
var dynamicdataObj = {
lists:[]
};
dynamicdataObj.getDynamicData = function(type){
var url = 'https://api.github.com/users/tomalex0/repos'
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
// concatenate without breaking reference that controllers will have
dynamicdataObj.lists.concat(response.data)
}, function errorCallback(response) {
});
};
// load the data when service initializes
dynamicdataObj.getDynamicData()
return dynamicdataObj;
});
答案 1 :(得分:0)
由于http响应是异步的。您需要从服务等待中获取一个承诺,并在成功解决承诺后分配$ scope.lists的值。
您的DynamicData Factory将
dynamicdataObj.getDynamicData = function(type){
var url = 'https://api.github.com/users/tomalex0/repos';
return $http({
method: 'GET',
url: url
});
};
并且您的FirstCtrl将变为:
function FirstCtrl($scope, Data, DynamicData) {
$scope.data = Data;
//Call GetDynamicData in service and wait till promise gets resolved or rejected.
DynamicData.getDynamicData()
.then(function(response){
//Promise resolved successfully in service, assign the returned data to my lists property
$scope.lists = response.data;
},function(err){
$scope.lists = [];
console.error('something bad happend');
})
$scope.toggleLike = function(item){
item.watchers_count = (item.watchers_count) ? (item.watchers_count+1) : 1;
}
}
我已经在这里更新了你的jsfiddle和FirstCtrl的注释: