angular 使用多种方法在控制器中注入服务

angular service injection in controller with multiple methods

我正在尝试正确构建面向对象的离子控制器,但遇到了服务注入问题...

angular.module('app.controllers', ['ionic', 'app.services.myservice']).controller('myCtrl', MyCtrl)

function MyCtrl($scope, $ionicLoading, MyService){
    this.scope = $scope;
    this.ionicLoading = $ionicLoading;
    this.MyService = MyService;
}

MapCtrl.prototype.method1 = function($scope, $ionicLoading, MyService)  {
    //$scope, $ionicLoading and MyService are undefined
}
MapCtrl.prototype.method2 = function(){
    this.scope.dummy = "A"; //That's ok!
    this.MyService.aMethodWithCallBack(function(res){
        //this.ionicLoading or this.MyService are undefined in this scope !
    }
}

你会如何正确处理它?

您的问题是您没有注入依赖项:

angular.module('app.controllers', ['ionic', 'app.services.myservice']).controller('myCtrl', ['$scope', '$ionicLoading', 'MyService', MyCtrl])

function MyCtrl($scope, $ionicLoading, MyService){

}

这应该有效

为了更清楚,我建议你这样声明控制器:

var controllers = angular.module('app.controllers', ['ionic', 'app.services.myservice']);

controllers.controller('myCtrl', ['$scope', '$ionicLoading', 'MyService', MyCtrl]);

function MyCtrl($scope, $ionicLoading, MyService){

}

我更喜欢下一种方式

MyCtrl.$inject = ['$scope', '$ionicLoading', 'MyService'];
function MyCtrl($scope, $ionicLoading, MyService) {
  // Act as ViewModel
  var vm = this;

  vm.method1 = function() {
    MyService.getData().then(function(response) {
      vm.data = response;
    });
  };
}