user5477154
user5477154

Reputation:

Angularjs routing to # causing problems

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.

Upvotes: 0

Views: 62

Answers (1)

charlietfl
charlietfl

Reputation: 171679

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

Upvotes: 1

Related Questions