user3668232
user3668232

Reputation: 51

Properly use custom angularjs service, function not defined error

I created my own service for some util methods. The idea was to simply inject the utilsservice into the modules where I need the methods. The Problem is I get an ReferrenceError: myFunction is not defined.

I think it has to do with the wrong injecting of the service, but i can't figute out myself what's wrong with my approach.

The service i made:

angular.module('utils',[]).service('UtilsService',function(){

    this.myFunction = function(){};  

});

In my app.js file i have following structure:

(function(){
    angular.module('utils',[]);
    angular.module('translation',[]);

    var app = angular.module('myApp',['translation','utils']);
    app.controller('myController',['$http',function($http,UtilsService){

        UtilsService.myFunction();

    }]);
});

The order I included the scripts in my .html file:

<script type="text/javascript" src="../Libraries/angular.min.js"></script>
<script type="text/javascript" src="../js/angular-js/services/utilService.js"></script>
<script type="text/javascript" src="../js/angular-js/app.js"></script>
<script type="text/javascript" src="../js/angular-js/translate.js"></script>

I already tried to change the order but it doesn't make any difference.

I am thankfull for any advice you may have!

Upvotes: 0

Views: 11478

Answers (1)

Rahul Garg
Rahul Garg

Reputation: 378

Please try the below. You will need to change the script references to point to the files where you have them. Once the index.html file has loaded, you should see the output "you called myFunction()" in the console window. That is being printed from within the service which shows it's being called correctly. I've also created a fiddle

index.html:

<!doctype html>
<html lang="en" ng-app="myApp">
    <head>
        <meta charset="UTF-8">
        <title>Directives</title>
    </head>
    <body>

        <div ng-controller="myController"></div>

        <script src="angular.js"></script>
        <script src="app.js"></script>
        <script src="utilsService.js"></script>
    </body>
</html>

app.js (I have moved the code out of the function you created since it wasn't working. Also, you had a typo for spelling anguar on the line that begins with var app. I have also removed the dependency for translation in my code since I didn't create any module by that name):

(function(){
    //angular.module('utils',[]);
    //angular.module('translation',[]);


});

var app = angular.module('myApp',['utils']);

app.controller('myController',['$scope', 'UtilsService',function($scope,UtilsService){

    UtilsService.myFunction();

}]);

utilsService.js:

angular.module('utils',[])
.service('UtilsService',function(){

    this.myFunction = function(){ console.log ('you called myFunction()')};  

});

Upvotes: 4

Related Questions