redeagle47 redeagle47 - 7 months ago 12
Javascript Question

Angular won't load my service module

I have the following three files for an app using Angular 1.5:

app.js

angular.module('myApp', ['ngRoute', 'myApp.service'])
.controller('AppController', AppController);

AppController.$inject = ['$scope', 'GreeterService'];

function AppController($scope, GreeterService) {
$scope.greeting = GreeterService.greet("World");
}


service.js

angular.module('myApp.service', [])
.factory('GreeterService', function() {
return {
salutation: 'Hello',
greet: function(name) {
return this.salutation + ' ' + name + '!';
}
};
});


and index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="">

</head>
<body>
<header>

</header>

<main ng-app='myApp'>
<div ng-controller="AppController">
{{ greeting }}
</div>
</main>

<footer>
<script src="libs/angular.js" charset="utf-8"></script>
<script src="libs/angular-route.min.js" charset="utf-8"></script>
<script src="js/app.js" charset="utf-8"></script>
</footer>
</body>
</html>


I cannot get the app to load properly, and I don't know why. app.js and service.js are in the same directory. I have made the modules for both, I'm injecting myApp.service in the dependencies for myApp, myApp.service defines a factory that returns an object to use as the singleton, and all of the names match. The error I'm getting in the console tells me myApp.service couldn't be loaded because it isn't available. myApp and myApp.service is using DI correctly, as far as I can tell, and I don't think it's the controller because it's not even getting that far. I really can't see what the problem is and I would appreciate some help.

Answer

You have not added the reference for service.js having the definition of your service in index.html

<!DOCTYPE html>

</header>

<main ng-app='myApp'>
    <div ng-controller="AppController">
        {{ greeting }}
    </div>
</main>

<footer>
    <script src="libs/angular.js" charset="utf-8"></script>
    <script src="libs/angular-route.min.js" charset="utf-8"></script>
    <script src="js/app.js" charset="utf-8"></script>
    <script src="js/service.js" charset="utf-8"></script>
</footer>

Comments