egzaell egzaell - 6 months ago 71
AngularJS Question

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.

Answer Source

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