I'm learning Angular and I don't like my current approach. The current controller uses first Geolocation service and when getLocation() is resolved, then the Pagination service is invoked with the location param. Is it any better solution to provide one service that query server with location? Can I integrate the Pagination service to call it through the Post factory with a resolved location?
angular.module('app').controller('MainCtrl',['$scope','Post','Pagination','Geolocation'
($scope, Post, Pagination, Geolocation) ->
$scope.posts = []
Geolocation.getLocation().then (location) ->
Pagination.paginate $scope, Post, 10, (postsRes) ->
$scope.posts.push posts for posts in postsRes
, params: {location: location}
])
angular.module('app').factory 'Post', ($resource) ->
$resource '/posts/:id.json', { id: '@id' }
angular.module('app').service "Geolocation", ['$q', '$window', ($q, $window) ->
@getLocation = ->
deferred = $q.defer()
return deferred.resolve @loc if @loc
if $window.navigator and $window.navigator.geolocation
$window.navigator.geolocation.getCurrentPosition (position) ->
@loc = position.coords
deferred.resolve position.coords
deferred.promise
]
angular.module('app').service 'Pagination', ->
@paginate = ($scope, @resource, @maxElemPerPage=10, @onNewPage, @query={}) ->
@page = 1
@canLoadNextPage = true
$scope.loadPage = (promise) =>
return promise.resolve() unless @canLoadNextPage
@load promise
@load = (promise) =>
@canLoadNextPage = false
q = angular.extend @query, page: @page
@resource.query q, (resources) =>
@canLoadNextPage = true if resources.length is @maxElemPerPage
@page++
@onNewPage resources if @onNewPage
promise.resolve() if promise
@load()
@