Reputation: 195
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.
Upvotes: 0
Views: 524
Reputation: 2197
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.
Upvotes: 1
Reputation: 2228
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
};
}
Upvotes: 1
Reputation: 2679
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();
}
Upvotes: 0