0

I need to create my own router like code in angularjs because I need to add routes dynamically using simple plugins system. I have navigation like this:

<ul>
    <li><a href="#page1">page1</a></li>
    <li><a href="#page2">page2</a></li>
</ul>

and my controller look like this:

app.controller('main', function($scope) {
    let set = () => {
        this.panel = location.hash.replace(/^#/, '');
    };

    $(window).on('hashchange', () => {
        $scope.$apply(set);
    });
    set();
});

I will show different panel depend on controller panel property.

but when I click on the link I've got #!#page1 how can I prevent #!# and have #page1 as hash? Or maybe just #!/page1 (but without adding router) because when I'm adding href="page1" I've got normal link to page that don't exists (outside of angular).

5
  • write $locationProvider.html5Mode(true); in .config() block Commented Aug 10, 2017 at 17:30
  • Possible duplicate of AngularJS routing without the hash '#' Commented Aug 10, 2017 at 17:50
  • @WilliamHampshire that different question because I don't use router. Commented Aug 10, 2017 at 17:57
  • ...maybe you should? Why roll your own here? Commented Aug 10, 2017 at 18:08
  • @DanielBeck as I've said in the question I need to add plugins, dynamic routes, so I do that by injecting components in html using twig. I can't use ui-router or ng-router because all routes need to be defined in config and I don't want to create js file as twig template because I'm using webpack. Commented Aug 10, 2017 at 18:20

1 Answer 1

2

Thats the hash bang you need to remove (#!). For that you need to add base tag in the index.html of yours

<base href="/">

and set @locationProvider html mode to true, for example:

angular.module('myApp').config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true); //activate HTML5 Mode
});

the last # i.e. (#page1) would be there as you are setting the id to traverse to that section

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

2 Comments

Now the problem is that href="/logout" don't redirect but use history API to change url.
In order to make normal ulrls work you need to add ng-click="$event.stopPropagation()"

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.