Angular-routing, direct URL navigation

2019-06-28 00:44发布

I have an angular app defined on my index.html file. Using angular-routing i am routing a link named /erez to load a view with a template. It's working inside the app - when I click the link to /erez from the navbar on index.html it works perfectly. But when I go directly to my.site.com/erez on the address bar, it gives 404. I understand why that is, having no server-side code, but is there a pure angular way of achieving direct urls? my routing code:

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

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider.
        when('/', {
            templateUrl: 'index.html',
            controller: 'mainCtrl'
        }).
        when('/erez', {
            templateUrl: 'erez2.html',
            controller: 'erezCtrl'
        }).
        otherwise({
            redirectTo: '/'
        });

    $locationProvider.html5Mode(true);
});

2条回答
唯我独甜
2楼-- · 2019-06-28 01:17

Try this, it should work now.

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

    app.config(function ($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'index.html',
                controller: 'mainCtrl'
            }).
            when('/erez', {
                templateUrl: 'erez2.html',
                controller: 'erezCtrl'
            }).
            otherwise({
                redirectTo: '/'
            });

        $locationProvider.html5Mode({ enabled: true, requireBase: false });
    });
查看更多
做个烂人
3楼-- · 2019-06-28 01:35

You can find lots of useful information from this link:

So either you need this base url tag inside the tag:

<base href="/" />

But be aware, this base tag may break the relative links in your code. Alternatively you can use:

$locationProvider.html5Mode({
  enabled: true,
  requireBase: false
});

Hope this helps.

查看更多
登录 后发表回答