0

Fairly new to angularjs, trying to make a single page application. The default page to load should be a home page, and I also want a home button to route to this page.

Nav bar in HTML:

<html ng-app="app">

...

<ul class="nav navbar-nav navbar-center">
    <li><a href="#">Home</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#contact">Contact</a></li>
</ul>

...

<div ng-view></div>

in app.module.js:

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

app.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'pages/home.html',
            controller: 'main',
            controllerAs: 'vm'
        })
        .when('/about', {
            templateUrl: 'pages/about.html',
            controller: 'about',
            controllerAs: 'vm'
        })
        .when('/contact', {
            templateUrl: 'pages/contact.html',
            controller: 'contact',
            controllerAs: 'vm'
        });
});

app.controller('main', main);
app.controller('about', about);
app.controller('contact', contact);

function main() {
    var vm = this;
    vm.message = "Home page";
}

function about() { //stuff }

function contact() { //stuff }

When the page loads, everything displays correctly, and the url is http://localhost:8007/#/

My problem is that when I click Home, the url becomes http://localhost:8007/# and nothing displays. About and Contact both work as intended.

I know I can just change my Home button to have href="#/" but that feels like I am targeting the symptoms, not the problem. I feel like I really shouldn't have to do that.

I have tried adding .when('', { to app.module.js, but this does nothing.

1
  • I'd use an otherwise route to handle the home view. This has the benefit of handling routes if the user edits the URL. #asdf would still be handled by the otherwise route. Commented Oct 22, 2015 at 19:12

1 Answer 1

1

Your home href will be <a href="#/">Home</a> which then translates to the path "/" you defined in $routeProvider.

Dont use href="#" anywhere in the app

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

7 Comments

otherwise({redirectTo: '/'}) .. the angular paths are everything after # or #! if you use hashbang for SEO
but you can't use # as href anywhere
ok... you got me there...have never tried it and just did. The router rejected the change and stayed on current path
ok..i was able to replicate that by pasting url into another tab. Never thought of this before actually. Could probably catch it in $routeChangeError egghead.io/lessons/angularjs-resolve-routechangeerror ... my guess is the path will be empty string
would put that into angular.module('app').run() not in a controller
|

Your Answer

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