0

假设我有 2 个 HTML 页面,foo.html并且bar.html.

内部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 -->

内部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 -->

正如预期的那样,当我单击任一页面中的链接时,它将打开相应的页面。现在,我想“AngularJSify”这个,这样点击一个链接只会更新div#content. 我试过这个:

$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>

但是打开foo.html也会加载foo.html?onlyContent=true这是不必要的,因为foo.html已经有内容了!

您可能会问,“为什么不使用 empty div#content?” 因为我想(1)减少加载额外文件,以及(2)即使 JS 被禁用也使内容可用。

在 Backbone.js 中,我可以使用:

Backbone.history.start({pushState:true, silent:true});

这基本上意味着,“如果页面已经加载,不要再次调用路由。” 我如何在 AngularJS 中实现这一点?

4

1 回答 1

0

内部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>

内部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>

在 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".

于 2012-09-21T15:00:53.210 回答