OtoLeo
OtoLeo

Reputation: 363

How can I invoke an angular service from a controller?

I have an angular module with the following code:

angular.module('sampleModule', [])

.service('myService', [function () {
    this.showAlert = function () {
        alert("Hello");
    };

    this.sum = function (a, b) {
        return a + b;
    };
}])

.controller('SampleCtrl', ['myService', '$scope', function ($scope, myService) {
    this.doSum = function () {
        var result = myService.sum(1, 2);
        alert(result);
    };
}]);

When I invoke doSum I get:

TypeError: myService.sum is not a function

Any ideas? Thanks!

Upvotes: 1

Views: 47

Answers (2)

Suneet Bansal
Suneet Bansal

Reputation: 2702

Issue with sequencing of injections are not proper. $scope should come before myService.

Correct code:
.controller('SampleCtrl', ['$scope', 'myService', function ($scope, myService) {
    this.doSum = function () {
        var result = myService.sum(1, 2);
        alert(result);
    };
}]);

Upvotes: 1

kukkuz
kukkuz

Reputation: 42352

Your controller DI is wrong- note the order of the arguments:

.controller('SampleCtrl', ['$scope', 'myService', function ($scope, myService) {
    this.doSum = function () {
        var result = myService.sum(1, 2);
        alert(result);
    };
}]);

Upvotes: 3

Related Questions