0

I don't understand why my routing doesn't work, the "otherwise" case is working, but when I click in one of the menu the routing doesn't automatically load the relative page. Can anyone help me to understand what's wrong with my code please?

This is the code relative to the routing part:

var myColors = angular.module('myFirstModule', ['ngRoute']);
myColors.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/home', {
      templateUrl: 'home.html'
    })
    .when('/directory', {
      templateUrl: 'directory.html',
      controller: 'myFirstModule'
    }).otherwise({
      redirectTo: '/directory'
    });
}]);

Here it is the HTML div where I put the links:

<ul>
    <li><a href="#/home">Home </a></li>
    <li><a href="#/directory">Directory</a></li>
</ul>    

Here is a Plunker of my full code

1

2 Answers 2

2

Since you are using AngularJS 1.6, you need to add a ! is your href routing.
Eg: href="#/home" becomes href="#!/home".

<ul>
    <li><a href="#!/home">Home</a></li>
    <li><a href="#!/directory">Directory</a></li>
</ul>    

If you want to remove this prefix, see this answer.

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

Comments

0

You are using the wrong controller name and also as @Mistalis told you have to include #! in your href. If you want to remove the ! just use $locationProvider.hashPrefix(''); in your config. Then you can use your href without !

JS

var myColors = angular.module('myFirstModule', ['ngRoute']);
myColors.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/home', {
      templateUrl: 'home.html'
    })
    .when('/directory', {
      templateUrl: 'directory.html',
      controller: 'myFirstController' //use your controller name here
    }).otherwise({
      redirectTo: '/directory'
    });
}]);

HTML

<ul>
    <li><a href="#!/home">Home </a></li>
    <li><a href="#!/directory">Directory</a></li>
</ul> 

Working Plunker: https://plnkr.co/edit/GAob2u4MdnzXXltTZMg2?p=preview

2 Comments

I'm new to AngularJS, do you have any good tutorial/example where I can learn it better? Moreover, as you see, if I make some changes in the directory page and then click to go in another page, after returning back, all the changes are deleted, there is any way to save the changes ? Thanks.
You can find some tutorials here stackoverflow.com/tags/angularjs/info . Better is go to docs.angularjs.org/guide/concepts and learn. If you need the data to persist, you should use localstorage.

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.