Ionic - 如何在控制器中访问backgroundGeoLocation插件

时间:2017-01-17 22:14:44

标签: angularjs cordova ionic-framework

我想在控制器中访问backgroundGeoLocation插件(https://github.com/mauron85/cordova-plugin-background-geolocation),而不是在app.js文件中。

以这种方式使用插件,它的工作原理。

 .run(function($ionicPlatform) {
          $ionicPlatform.ready(function() {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins.Keyboard) {
              cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
              cordova.plugins.Keyboard.disableScroll(true);
            }
            if (window.StatusBar) {
              // org.apache.cordova.statusbar required
              StatusBar.styleDefault();
            }
          });

          document.addEventListener("deviceready", function () {
            backgroundGeoLocation.configure(callbackFn, failureFn, {
              desiredAccuracy: 10,
              stationaryRadius: 20,
              distanceFilter: 30,
              locationService: 'ANDROID_DISTANCE_FILTER',
              debug: false,
              stopOnTerminate: false
            });
          });
})

但是,在app.js中的.run之外,插件没有定义,就像在我的控制器中一样:

angular.module('starter.login', [])

 // Controller de connexion
.controller('LoginCtrl', function($scope, $timeout, $ionicPopup, $state, LoginService) {
  $scope.data = {};
  backgroundGeoLocation.configure(callbackFn, failureFn, {
      desiredAccuracy: 10,
      stationaryRadius: 20,
      distanceFilter: 30,
      locationService: 'ANDROID_DISTANCE_FILTER',
      debug: false,
      stopOnTerminate: false
    });
});

有没有办法在我的控制器中使用插件?

1 个答案:

答案 0 :(得分:0)

控制器中代码的问题在于它将在控制器初始化时执行 - 即在运行时 - 但Cordova插件是动态加载的,因此在deviceready事件触发之前不可用。这就是你的第一个代码块工作的原因,因为调用放在deviceready回调中(实际上你可以把它放在现有的$ionicPlatform.ready回调中 - 它会在同一个事件上触发)。您需要在控制器中执行类似的操作,即在尝试调用插件之前等待deviceready

angular.module('starter.login', [])

 // Controller de connexion
.controller('LoginCtrl', function($scope, $timeout, $ionicPopup, $state, LoginService, $ionicPlatform) {
  $scope.data = {};

  $ionicPlatform.ready(function() {
    backgroundGeoLocation.configure(callbackFn, failureFn, {
      desiredAccuracy: 10,
      stationaryRadius: 20,
      distanceFilter: 30,
      locationService: 'ANDROID_DISTANCE_FILTER',
      debug: false,
      stopOnTerminate: false
    });
  });
});