控制器中的角度服务注入有多种方法

时间:2015-02-27 10:02:58

标签: javascript angularjs ionic

我正在尝试正确构建面向离子对象的控制器,并且在使用Service Injection时遇到了麻烦...

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 !
    }
}

你会怎么处理呢?

2 个答案:

答案 0 :(得分:0)

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

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){

}

答案 1 :(得分:0)

我更喜欢下一个方式

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;
    });
  };
}