0

My Angular Routing Function is not working - There is a page load, but without the 'home.html' file. This is my code:

Index.html

<html  ng-app="App" class="no-js" lang="en" >
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
    <script src="app.js"></script>    
  </head>

  <body ng-cloak> 
  <div ng-controller="main">
      <div ng-view></div>
    </div>
  </body>
</html>

app.js

(function () {
'use strict';

angular
    .module('App', ['ngRoute']) 
    .controller('$routeProvider', router)
    .controller('main', main);

function router($routeProvider) {

    $routeProvider.
          when('/', {
            templateUrl: '_pages/home.html',
            controller: 'main'
          });

};
function main ($scope) {
console.log("done");
}
5
  • Are you sure the directory structure is correct? EDIT: is this node file in the same directory as the _pages folder? Commented Apr 27, 2016 at 20:01
  • Directory should be fine - home.html is in a subfolder (file above: index.html is one folder level up) Commented Apr 27, 2016 at 20:08
  • 2
    the router stuff should be in .config call, you have it in a controller Commented Apr 27, 2016 at 20:18
  • docs.angularjs.org/tutorial/step_07 Commented Apr 27, 2016 at 20:19
  • when I change controller to config, then there is a '[$injector:modulerr]' error... Commented Apr 27, 2016 at 20:21

2 Answers 2

3

Angular $providers working just in config state. Eg:

angular
.module('App', ['ngRoute']) 
.config(['$routeProvider', router]);
function router($routeProvider) {

    $routeProvider.
      when('/', {
        templateUrl: '_pages/home.html',
        controller: 'main'
      });

};
Sign up to request clarification or add additional context in comments.

Comments

3

The route configuration is done in config and not controller. Change your code as below:

(function () {
  'use strict';

   angular
    .module('App', ['ngRoute']) 
    .config(router)
    .controller('main', main);

  function router($routeProvider) {

    $routeProvider.
      when('/', {
        templateUrl: '_pages/home.html',
        controller: 'main'
      });

  };

  function main ($scope) {
    console.log("done");
  }
});

1 Comment

Oops. We answered in same time. Your solution is great. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.