将AngularJS Scope与其他服务引用

时间:2015-02-16 00:28:04

标签: javascript angularjs scope geolocation

我正在开发一个AngularJS项目,我的服务遇到了一些麻烦。我创建了一个返回两个函数的服务。一个返回用户的当前位置,另一个返回API URL。我面临的问题是API URL需要纬度和经度。我想获取当前位置数据并将其传递到网址,并将数据绑定到我的视图。如何将每个服务的范围引用到另一个服务? 继承我的代码:

angular.module('myApp', [])

.controller('HomeCtrl', ['$scope', '$q', '$http', 'myService',
  function($scope, $q, $http, myService) {

    myService.getLocation().then(function(data) {
      $scope.lat = data.coords.latitude;
      $scope.long = data.coords.longitude;
      console.log($scope.lat, $scope.long);
    });
    myService.getAirports().then(function(data) {

    });
  }
])

//MYSERVICE FACTORY
.factory('myService', function($http, $q, $cordovaGeolocation) {
  return {
    getLocation: function() {
      var deferred = $q.defer();
      $cordovaGeolocation.getCurrentPosition().then(function(position) {
        var lat = position.coords.latitude;
        console.log(lat);
        deferred.resolve(position)
      });
      return deferred.promise;
    },


    getAirports: function() {
      var deferred = $q.defer();
      var url = 'https://api.flightstats.com/flex/airports/rest/v1/jsonp/withinRadius/' + PLACE LONGITUDE HERE + '/' + PLACE LONGITUDE HERE + '/10?appId=02a5e867&appKey=1f2075112529890985b1dd8ea0f0a419' + '&callback=JSON_CALLBACK';
      var config = {
        method: 'GET',
        callback: 'JSON_CALLBACK'
      }
      $http.jsonp(url, config)
        .then(function(data) {
          var lat = data.data.airports[0].latitude;
          deferred.resolve(data)
        });
      return deferred.promise;
    }
  }
});

JSFiddle

如果我可以做些什么来简化我的代码,请告诉我。

1 个答案:

答案 0 :(得分:0)

您需要在第一个服务的then方法中调用第二个服务并传入lat / lng数据:

myService.getLocation().then(function(data){
    $scope.lat = data.coords.latitude;
    $scope.long = data.coords.longitude;
    console.log($scope.lat, $scope.long);
    myService.getAirports($scope.lat, $scope.long).then(function(data){

    });
});

然后你可以使用getAirports方法中的数据:

getAirports: function(lat, lng) {
 ....
 var url = 'https://api.flightstats.com/flex/airports/rest/v1/jsonp/withinRadius/'+ lat+'/'+lng+'/10?appId=02a5e867&appKey=1f2075112529890985b1dd8ea0f0a419' + '&callback=JSON_CALLBACK';
 ....
}