12

Aアンカータグ内で他の AngularJS アプリケーションの場所にリンクするにはどうすればよいですか? HTML5 ハッシュレス モードを使用していますが、ページが実際にリロードされるのを避けたいと考えています。

たとえば、HTML5 以外のモードでは、次のようにします。

<a href='#/path'>Link</a>

HTML5 モードでは、次のことができます。

<a href='/path'>Link</a>

しかし、実際にはこれにより、ブラウザは新しい URL を再読み込みします。私も構文を使用してみましng-href/#/pathが、どれも私が望むように機能していないようです。

アンカータグから適切にリンクするにはどうすればよいですか?

4

3 に答える 3

17

Update:

It seems like this is possible without using $location, you just have to keep the same base link. From the docs:

When you use HTML5 history API mode, you will need different links in different browsers, but all you have to do is specify regular URL links, such as: <a href="/some?foo=bar">link</a>

When a user clicks on this link,

  • In a legacy browser, the URL changes to /index.html#!/some?foo=bar
  • In a modern browser, the URL changes to /some?foo=bar

In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.

  • Links that contain target element. Example: <a href="/ext/link?a=b" target="_self">link</a>
  • Absolute links that go to a different domain. Example: <a href="http://angularjs.org/"></a>
  • Links starting with '/' that lead to a different base path when base is defined. Example: <a href="/not-my-base/link">link</a>

Old:

You should use the $location service. Inject it into the controller and put it on the $scope (or in a convenience method):

function MainCtrl($scope,$location){
  $scope.goto = function(path){
    $location.path(path);
  }
}
<a ng-click="goto('/path')">Link</a>
于 2013-05-14T13:49:28.870 に答える