Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This code is used to get the users location and deliver it as a resource to the controller. The aim is to have this data shared across multiple controllers in the application. So far this does deliver the data as a parameter of the then() method on the promise. Is this pattern a suitable way of sharing a resource which is delivered through a promise? Any feedback would be greatly appreciated.

angular.module('geolocation', [])
.factory('geolocation', function ($q, $window) {
    return {
        getLocation: function () {
            var deferred = $q.defer();

            $window.navigator.geolocation.getCurrentPosition(function(position){
                deferred.resolve(position);
            }); 

            return deferred.promise;
        }
    };
});

angular.module('nearestLocationCtrl', [
    'geolocation'
])
.controller('NearestLocationCtrl', ['$scope', 'geolocation', function ($scope, geolocation) {
    geolocation.getLocation().then(function (data) {
        console.log(data);
    });
}]);
share|improve this question

You can use resolve feature of ui-router (https://github.com/angular-ui/ui-router/wiki) or ngRoute. Promise will be resolved and injected into controller automatically, service and controller will be nicely decoupled. Using ui-router code would look like this:

app.controller('NearestLocationController', function($scope, location) {
}

$stateProvider.state('locationState', {
      resolve: {
         location: function(geolocation){
            return geolocation.getLocation();
         }
      },
      controller: 'NearestLocationController'
})
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.