在我的 Angular.js 应用中,我有一个父控制器,它会生成我现在的longitude and latitude
,以便我可以将这些数据存入我的子控制器。我的代码如下:
家长控制器
(function() {
'use strict';
angular.module('app').controller('InitCtrl', InitCtrl);
function InitCtrl() {
var init = this;
init.g_map = {};
init.g_map.current = {};
let geocoder = new google.maps.Geocoder();
// current latitude & longitude
navigator.geolocation.getCurrentPosition(function(position) {
init.g_map.current.lat = position.coords.latitude;
init.g_map.current.lng = position.coords.longitude;
});
}
})();
儿童控制器
(function() {
'use strict';
angular.module('app').controller('ListCtrl', ListCtrl);
function ListCtrl($scope, $timeout, _, NgMap, RestaurantApi) {
let list = this;
list.load = function load() {
let init = $scope.$parent.init;
list.res = {};
list.res = init.g_map.current;
console.log("list.res 1: ", list.res);
/* Output (console window):
list.res 1 : >Object{}
{
lat: 'my-current-lat'
lng: 'my-current-lng'
}
// here I have got my parent controller data
*/
// but in the following console, I got undefine
// even if I already got data which is printed previous console
console.log("list.res 2 : ", list.res.lat, list.res.lng);
/* Output (console window)
list.res 2 : undefined undefined
*/
}
list.load();
}
})();
我不明白为什么会这样,有什么建议吗?
答案 0 :(得分:0)
我在lat: 'my-current-lat'
控制台输出后丢失了一个逗号。也许有一个隐藏的错误?
您可以尝试使用以下语法访问属性:
console.log('list.res 2: ', list.res['lat'], list.res['lng']);
答案 1 :(得分:0)
获取该位置的函数是异步的,因此您尝试在拥有它们之前访问其属性。试试promises的文档。
我有一个很好的例子,说明如何在这种情况下使用承诺,请查看此jsfiddle.net/0bghsjf8/,如果您还有其他需要,请告诉我。