简体   繁体   中英

AngularJs calling service function from controller

I've got some app in AngularJs, and I've encountered a problem. I need to call a function from service in controller.

my service:

var DataService = ['$http', '$q', '$window', 'alert', function ($http, $q, $window, alert) {
    function print () {
        console.log('smth');
    }
}

my controller:

var Controller = function ($scope, $state, OffersService, commonFunction, dataService, alert, blockUI) {
    function printSmth () {
        dataService.print();
    }
}

function printSmth is called from ng-init in html, and I get exception saying that dataService.print is not a function.

Does anybody know the proper way to do it? I can't change it to .service it must be done this way.

try like below..

var DataService = ['$http', '$q', '$window', 'alert', function ($http, $q, $window, alert) {
   this.print = function () {
        console.log('smth');
    };
}

or

var DataService = ['$http', '$q', '$window', 'alert', function ($http, $q, $window, alert) {
       function print() {
            console.log('smth');
        };
       return {
        print: print
       };
}

The best way to what you want to accomplish would be something like:

Service:

/* recommended */

// dataservice factory
angular
    .module('app.core')
    .factory('dataservice', dataservice);

dataservice.$inject = ['$http', '$q', '$window', 'alert'];

function dataservice($http, $q, $window, alert) {
    return {
        print : print 
    };

    function print () {
        console.log('smth');
    }
}

Controller:

/* recommended */

// controller calling the dataservice factory
angular
    .module('app.avengers')
    .controller('YourController', YourController);

YourController.$inject = ['$scope', '$state', 'OffersService', 'commonFunction', 'dataservice', 'alert', 'blockUI'];

function YourController($scope, $state, OffersService, commonFunction, dataservice, alert, blockUI) {
    $scope.printSmth = function printSmth() {
           dataService.print();
    };
}

I recommend you start reading some style guides for AngularJS . You will make your life and your development team more productive in the future.

var Controller = function ($scope, $state, OffersService, commonFunction, dataService, alert, blockUI) {

Change dataService to DataService

----------------UPDATE--------------------

The function you have defined in controller cannot be accessed in view unless its a $scope function.

So make the print function in your controller to be

$scope.printSmth = function () {
    dataService.print();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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