在routeProvider中链接`href ='#'时阻止页面模板更改

时间:2014-08-28 05:03:38

标签: javascript angularjs twitter-bootstrap route-provider

我一直在将我的项目从JQuery迁移到Angular.js

我有几个针对'#'的链接,例如在bootstrap下拉列表中:

<a href="#" class="dropdown-toggle" data-toggle="dropdown">                                 
    Administrator <b class="caret"></b>
</a>
<ul class="dropdown-menu">
    <li><a href="info.html">Info</a></li>
    <li><a href="settings.html">Settings</a></li>
    <li class="divider"></li>
    <li>
      <a id="logout" href="logout.html">
        <span class="glyphicon glyphicon-off"></span> Logout
      </a>
    </li>
</ul>

我尝试使用angular routeProvider

实现页面路由
$routeProvider.when('/content/chat', {
  templateUrl: config.indexURL + 'content/chat',
  controller: 'ChatCtrl'
})
.otherwise({ redirectTo: '/' });;

当链接定位到“#”时页面会不断变化,同时我想让它们不被重定向

我有一个解决方案,我们可以将href属性更改为javascript:void(0);

href="#" causes location address to change, can we avoid it?

但是我的页面中有很多以#为目标的链接(其中许多是由JQuery插件生成的) 我不想一个一个地改变它。

在routeProvider设置中链接href='#'时是否有办法阻止页面更改?

1 个答案:

答案 0 :(得分:0)

当您点击#时,您想要 以允许页面更改(默认)行为。您需要重写代码以跳转到旧#的页面行为的一部分。

为此,您可以使用Angular的$anchorScroll。这是一个例子(摘自他们的网站)

<div id="scrollArea" ng-controller="ScrollController">
  <a ng-click="gotoBottom()">Go to bottom</a>
  <a id="bottom"></a> You're at the bottom!
</div>

你的控制器是:

angular.module('anchorScrollExample', [])
  .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
    function ($scope, $location, $anchorScroll) {
      $scope.gotoBottom = function() {
        // set the location.hash to the id of
        // the element you wish to scroll to.
        $location.hash('bottom');

        // call $anchorScroll()
        $anchorScroll();
      };
    }]);
相关问题