【发布时间】:2015-02-23 13:07:18
【问题描述】:
我在 Angular.js 工厂中有一个对象:
angular.module('myapp')
.factory('geoLocationService', function () {
var geoLocationObj = {};
var geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(_successFunction, _errorFunction);
}
function _successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[2]) {
geoLocationObj.resultCity = results[2].formatted_address;
alert(geoLocationObj.resultCity);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
return geoLocationObj;
});
这适用于alert(geoLocationObj.resultCity); 并在属性值中发出警报
但是
console.log(geoLocationObj);
不记录属性geoLocationObj.resultCity
我试图在我的控制器中的工厂外使用geoLocationObj.resultCity,但它不存在。
我的控制器中有:
.controller('IndexCtrl', function ($scope, geoLocationService) {
var geoLocationService = geoLocationService;
console.log(geoLocationService);
geoLocationService 是一个空对象
我无法弄清楚为什么会这样。 你能帮我解决这个问题吗?
【问题讨论】:
标签: javascript angularjs object