我正在尝试正确构建一个 ionic 面向对象的 Controller ,但在服务注入(inject)方面遇到了麻烦......
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 !
}
}
你会如何正确处理它?</p>
最佳答案
我更喜欢下一种方式
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;
});
};
}
关于javascript - 具有多种方法的 Controller 中的 Angular 服务注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28762317/