Search code examples
javascriptangularjsangularjs-service

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!


Solution

  • 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);
        };
    }]);