简体   繁体   English

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

[英]angular service injection in controller with multiple methods

I'm trying to build a ionic object-oriented controller properly and am getting trouble with 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 !
    }
}

How would you handle it, properly? 您会如何正确处理?

Your issue is that you did not inject the dependencies : 您的问题是您没有注入依赖项:

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

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

}

This should work 这应该工作

To make it more clear, I suggest you to declare controllers that way : 为了更清楚一点,我建议您以这种方式声明控制器:

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

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

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

}

I prefer next way 我喜欢下一条路

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM