Ivan
Ivan

Reputation: 1783

Angular ng-include strange behavior - causing URL address change

I've noticed a strange behavior of ng-include -- it is causing a strange side effect on the browser in some cases.

Here is a page, that contains a simple twitter bootstrap tab pane

<body>
    <ul class="nav nav-tabs">
        <li class="active"><a href="#tab1" data-toggle="tab">Tab 1</a></li>
        <li><a href="#tab2" data-toggle="tab">Tab 2</a></li>
    </ul>
    <div class="tab-content">
        <div class="tab-pane active" id="tab1">AAA</div>
        <div class="tab-pane" id="tab2">BBB</div>
    </div>
</body>

Now, if I add ng-include anywhere in the page, for example at the beginning of the page:

<body>
    <ng-include src="'page1.html'"></ng-include>
    ...

It doesn't matter what the included file contains, it can be even empty, but this will cause each click when switching tabs to add #/tab1, #/tab2, etc. to the page URL. This happens in all browsers, which is undesirable. On Chrome, this also causes the tab icon to flicker, and for a moment it shows default white icon before it reloads the page specific icon.

Anyone experienced something similar? Why adding ng-include would cause this? I also tried doing the include without angular (by using jQuery.load()) and there is no issue seen.

This can be fully experienced on a standalone page, but on this plnkr page I created, although one cannot see the URL, and the flicker effect in Chrome is less visible, but still the effect can be seen in Chrome.

Upvotes: 2

Views: 559

Answers (1)

runTarm
runTarm

Reputation: 11547

The url changing behavior come from the $location service, which is used by ng-include. So you could be able to reproduce it by just injecting the $location service somewhere in your app.

See the What does it do? section of this $location guide, and the action that causing the problem is:

  • Maintains synchronization between itself and the browser's URL when the user clicks on a link in the page

This answer your question "Why adding ng-include would cause this?".

To prevent the url from changing by the $location service, you could do it like this:

appModule.run(function ($rootScope) {
  $rootScope.$on('$locationChangeStart', function ($event, newUrl, oldUrl) {
    // may add some logic here to prevent url changes only that come from clicking tab.
    $event.preventDefault();
  });
})

Example plunker: http://plnkr.co/edit/4289uwL1mHSRj6oP4dl1?p=preview

Hope this helps.

Upvotes: 2

Related Questions