我正在尝试将两个范围合并为一个具有不同标签集的范围。不确定这是否可行,但到目前为止这是我的代码。
.controller('eventsCtrl', ['$scope', '$rootScope', '$http', 'getEventType1', 'getEventType2',
function ($scope, $rootScope, $http, getEventType1, getEventType2) {
$scope.createData = function () {
//initialise all the things
var eventsType1 = [];
var eventsType1 = [];
$scope.events1 = [];
$scope.events2 = [];
var eventsListArray = [];
$scope.events = [];
//fetch the data
var myEventsType1 = getEventType1.fetch(function (events1) {
$scope.events1 = events1;
});
var myEventsType2 = getEventType2.fetch(function (events2) {
$scope.events2 = events2;
});
var theEvents1 = $scope.events1;
var theEvents2 = $scope.events2;
angular.forEach(theEvents1, function (event, event1) {
count += 1;
console.log('iteration ' + count);
eventsListArray.push({
event_id: event1.id,
event_name: event1.name,
event_category: event1.category,
event_type: 'Type A',
event_date: event1.date
});
});
angular.forEach(theEvents2, function (event, event2) {
eventsListArray.push({
event_id: event2.id,
event_name: event2.name,
event_category: event2.category,
event_type: 'Type B',
event_date: event2.date
});
//$scope.events.push(event2);
});
$scope.events = eventsListArray;
}
$scope.createData();
}])
(实际上,event1和event2彼此之间的差异比它们在这个例子中的显示更加不同,并且它们需要相互区分)
通过两种不同的服务从服务器获取数据。
答案 0 :(得分:1)
如果我正确理解了您的问题陈述,您希望从$http
服务调用中获取两个不同的列表并迭代这两个列表并将它们添加到主范围变量中,这将使这两个列表与所需对象合并。 / p>
然后进行一些更改,如下所述,$http
调用在您$scope.events = eventsListArray;
函数中createData()
执行服务调用尚未完成的时候是异步的,结果将是空数组。
要避免这种情况,请将迭代部分保留在服务调用本身中,等待我们获取数据,然后将整个列表分配给主范围变量。
如下所示更改您的控制器,这将达到预期的效果
var app = angular.module('myApp', []);
app.controller('eventsCtrl', ['$scope', '$rootScope', '$http', 'getEventType1', 'getEventType2',
function($scope, $rootScope, $http, getEventType1, getEventType2) {
$scope.createData = function() {
//initialise all the things
var eventsType1 = [];
var eventsType2 = [];
$scope.events1 = [];
$scope.events2 = [];
var eventsListArray = [];
$scope.events = [];
//fetch the data
var myEventsType1 = getEventType1.fetch(function(events1) {
$scope.events1 = events1;
var theEvents1 = $scope.events1;
angular.forEach(theEvents1, function(event, event1) {
count += 1;
console.log('iteration ' + count);
eventsListArray.push({
event_id: event1.id,
event_name: event1.name,
event_category: event1.category,
event_type: 'Type A',
event_date: event1.date
});
});
$scope.events = eventsListArray; //lets assign to the scope varaible as we dont know which requests complete first..
});
var myEventsType2 = getEventType2.fetch(function(events2) {
$scope.events2 = events2;
var theEvents2 = $scope.events2;
angular.forEach(theEvents2, function(event, event2) {
eventsListArray.push({
event_id: event2.id,
event_name: event2.name,
event_category: event2.category,
event_type: 'Type B',
event_date: event2.date
});
});
$scope.events = eventsListArray;//same as above mentioned reason in the end we will have whole list from both async calls..
});
}
$scope.createData();
}
])