sai123
sai123

Reputation: 105

AngularJS service dependency injection error

<!DOCTYPE html>
<html ng-app="myApp">

<head></head>
<head>

</head>

<!-- ControllerAs syntax -->
<!-- Main controller with serveral data used on diferent view -->
<body ng-controller="MainCtrl as main" class="{{$state.current.data.specialClass}}" landing-scrollspy id="page-top">

<!-- Main view  -->
<div ui-view></div>

<!-- jQuery and Bootstrap -->
<script src="js/jquery/jquery-3.1.1.min.js"></script>
<script src="js/plugins/jquery-ui/jquery-ui.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>

<!-- Anglar App Script -->
<script src="js/app.js"></script>
<script src="js/config.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services/myService.js"></script>
</body>
</html>

I have an angularJS app which was working fine before adding a service. I am getting the following error. myService.js:3 Uncaught Reference Error: myApp is not defined Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.0/$injector/modulerr? I am tying all the controllers to the module. I have also added the myService file to the index.html Below is the code that I have in controller:

function MainCtrl($scope, $rootScope, $http, $state, myService){
};

angular
    .module('myApp')
    .controller('MainCtrl', MainCtrl)
    .controller('FinalViewCtrl', FinalViewCtrl);

This is what I have in myService.js
    'use strict';
    myApp.factory('myService', ['$http', function($http) {
    }]);

Let me know if I am missing anything?

Upvotes: 0

Views: 1216

Answers (2)

Tyler
Tyler

Reputation: 1039

Without the html, it will be hard to tell, but are you adding your JavaScript files in the correct order? You have to make sure that your file with angular.module('myApp') is loaded before any controllers or services. I've had the same error you have when adding my service before my app.

Upvotes: 0

Kalyan
Kalyan

Reputation: 1200

Add the myapp variable initiation just above the service code.

var myapp = angular.module('myApp');
   myApp.factory('myService', ['$http', function($http) {
    }]);

Upvotes: 1

Related Questions