Say I have 2 HTML pages, foo.html
and bar.html
.
Inside foo.html
:
<a href="/foo.html" class="selected">Open Foo</a>
<a href="/bar.html">Open Bar</a>
<!-- shared content -->
<div id="content">Nested HTML specific to Foo</div>
<!-- shared content -->
Inside bar.html
:
<a href="/foo.html">Open Foo</a>
<a href="/bar.html" class="selected">Open Bar</a>
<!-- shared content -->
<div id="content">Nested HTML specific to Bar</div>
<!-- shared content -->
As expected, when I click a link in either page, it will open the corresponding page. Now, I want to "AngularJSify" this so that clicking a link will only update div#content
. I tried this:
$routeProvider
.when('/foo.html', {templateUrl:'/foo.html?onlyContent=true'})
.when('/bar.html', {templateUrl:'/bar.html?onlyContent=true'})
<div id="content" ng-view>Nested HTML specific to Foo (or Bar, depending which page you're in)</div>
But opening foo.html
will also load foo.html?onlyContent=true
which is unnecessary because foo.html
already has the content!
You might be asking, "Why not use empty div#content
?" Because I want to (1) Reduce loading extra file, and (2) Make the content available even if JS is disabled.
In Backbone.js I can use:
Backbone.history.start({pushState:true, silent:true});
Which basically means, "If the page is already loaded, don't invoke the route again." How do I achieve that in AngularJS?
Inside foo.html
:
<a href="/foo.html" class="selected">Open Foo</a>
<a href="/bar.html">Open Bar</a>
<div id="defaultTemplate">Nested HTML specific to Foo</div> <!-- note this -->
<div id="content" ng-view></div>
Inside bar.html
:
<a href="/foo.html">Open Foo</a>
<a href="/bar.html" class="selected">Open Bar</a>
<div id="defaultTemplate">Nested HTML specific to Bar</div> <!-- note this -->
<div id="content" ng-view></div>
In JavaScript:
function routing(path, controller, template) {
var route = {templateUrl:'/templates/' + path, controller:controller};
if (path === window.location.pathname) {
var defaultTemplate = $('#defaultTemplate');
route = {template:defaultTemplate.html(), controller:controller};
defaultTemplate.remove();
}
$routeProvider.when(path, route);
}
Essentially means, "if the route you're opening is the same with the path in address bar, use template from current page instead".