Greg
Greg

Reputation: 1710

How to separate routes in angularjs

So i created a simple app.js like this

var app = angular.module('app', ['ngRoute', 'ngResource']);


app.config(function ($routeProvider) {

  $routeProvider

      .when('/', {
        templateUrl: 'html/home.html',

      });


});

but when i create a separate file routes.js

app.config(function ($routeProvider) {

    $routeProvider
    .when('/', {
        templateUrl: 'html/home.html',

});


});

The homepage is not shown. I double checked everything and i added the routes.js to the index page.

But it gives me this error : Uncaught ReferenceError: app is not defined. But i don't know why? the app is not an anonymous function.

This is my index page

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

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <script type="text/javascript" src="https://code.angularjs.org/1.4.4/angular.js"></script>
    <script type="text/javascript" src="https://code.angularjs.org/1.4.4/angular-resource.js"></script>
    <script type="text/javascript" src="https://code.angularjs.org/1.4.4/angular-route.js"></script>
    <script type="text/javascript" src="routes.js"></script>
    <script type="text/javascript" src="app.js"></script>

</head>
<body>

<div ng-view></div>

</body>
</html>

Upvotes: 0

Views: 1315

Answers (1)

dfsq
dfsq

Reputation: 193261

Since you use app variable in routes.js you need to load this file after app.js where this variable is created:

<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="routes.js"></script>

Alternatively you could setup routes in separate modules and use those modules as dependencies to main module:

var app = angular.module('app', ['ngRoute', 'ngResource', 'main', 'admin']);

and then for example in main-moudle.js:

angular.module('main', []).config(function ($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: 'html/home.html',
});

Upvotes: 3

Related Questions