我正在加載Google地圖,當我導航到/地圖時,它會加載標記以填充地圖。問題是JavaScript的其餘部分在加載標記之前運行並執行。我認爲解決這個問題的方法是在檢索地圖數據的工廠返回一個承諾。這雖然沒有奏效。我的角廠承諾有什麼問題?
任何人都可以建議我做錯了什麼?
在控制檯中我看到這一點:
angular.js:13920 TypeError: Cannot read property 'lat' of undefined
at Object.link (http://localhost/logintest/js/app.js:586:55)
586線是指這條線(該指令):
center: new google.maps.LatLng(lastElement.lat, lastElement.lon),
我得到了lastElement
像這樣:
var lastElement = scope.arrLocations[scope.arrLocations.length - 1];
工廠:
app.factory('map', ['$q', function($q){
var map={};
var mapInfoItems=[];
map.getMapInfo = function() {
var deferred = $q.defer();
var mapitems = firebase.database().ref('mapinfo/'+firebase.auth().currentUser.uid);
mapitems.on('child_added', function(snapshot){
mapInfoItems.push(snapshot.val());
deferred.resolve(mapInfoItems);
});
return deferred.promise;
};
return map;
}]);
控制器:
app.controller('mapController', ['$scope', 'map', function($scope, map){
$scope.myLocations = {};
$scope.arrLocations = [];
$scope.mapLocations = map.getMapInfo();
for(var i=0; i<$scope.mapLocations.length; i++){
$scope.myLocations.title = $scope.mapLocations[i].name;
$scope.myLocations.content = $scope.mapLocations[i].message;
$scope.myLocations.lat = $scope.mapLocations[i].lat;
$scope.myLocations.lon = $scope.mapLocations[i].lon;
$scope.arrLocations.push($scope.myLocations);
}
}]);
HTML:
<div ng-controller="mapController">
<my-map get-map-fn="getMap()"></my-map>
</div>
是什麼控制檯說? –
我已經添加了更多的細節。 – user1532669
好吧,所以'arrLocations'的創建有些問題。讓我們在控制檯中記錄前一步,看看它的樣子。也許'console.log($ scope.myLocations);' –