HTML <a href="#hash"> in AngularJS

时间:2017-08-23 03:34:05

标签: html angularjs angular-ui-router hashref

I have an issue with the <a href="#"> in my AngularJS app.

My main issue is on the:

<a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><em class="fa fa-bars"></em></a>

navigation.html -> this is a template of navigation directive.

<nav class="sidebar col-xs-12 col-sm-4 col-lg-3 col-xl-2 bg-faded sidebar-style-1">
<h1 class="site-title"><a href="index.html"><em class="fa fa-rocket"></em> Brand.name</a></h1>

<a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><em class="fa fa-bars"></em></a>

<ul class="nav nav-pills flex-column sidebar-nav">
    <li class="nav-item"><a class="nav-link active" href="index.html"><em class="fa fa-dashboard"></em> Dashboard <span class="sr-only">(current)</span></a></li>
</ul>

<a href="#" class="logout-button"><em class="fa fa-power-off"></em> Signout</a></nav>

index.html

<body ng-app="test" class="body-bg" ng-style="bgimg" ui-view>
</body>

app.js

var app = angular.module("test", ["ui.router");

app.config(function($stateProvider, $urlRouterProvider){
    $urlRouterProvider.otherwise('/');
    $stateProvider

        // login route
        .state("login", {
        url:"/",
        controller: "LoginController",
        templateUrl: "pages/login/login.html"
        })
        // admin route
        .state("admin", {
        url:"/admin",
        controller: "AdminController",
        templateUrl: "pages/admin/admin.html"
        })

And currently I am doing a SPA routing using ui-sref of ui-router. The problem is everytime I click the button, I get redirected to the default state $urlRouterProvider.otherwise('/');.

How I can do something similar to that HTML href="#" with AngularJS ui-sref?

Or is there other ways?

4 个答案:

答案 0 :(得分:1)

如果你有jQuery(你可能会这样做) 在你头上的标签......

<script>
    $(document).ready(function(){
        $('[href="#menu-toggle"]').click(function(event){

             event.preventDefault();
        })

    });
</script>

基本上通过窗口导航保持链接路由。 您可以通过将此代码粘贴到浏览器控制台中轻松进行测试..

$('[href="#menu-toggle"]').click(function(event){

         event.preventDefault();
    })

答案 1 :(得分:1)

从问题中的代码我可以说,href的正常使用会导致重定向,所以你需要使用data-target,你能试试吗?

<a  data-target="#menu-toggle" data-toggle="collapse" class="btn btn-default"><em class="fa fa-bars"></em></a>

JSFiddle: here

答案 2 :(得分:0)

您可以结合使用hrefng-click来解决问题。

<a href="" class="logout-button" ng-click="signOut()"><em class="fa fa-power-off"></em> Signout</a></nav>

signOut()是控制器上的一个功能。

答案 3 :(得分:0)

1.只需从锚标记中完全删除href标记。没有它,它仍然是一个非常有效的标签。 (或)href =&#34; javascript:void(0);&#34;

供您参考:Angular-UI-Router: should i avoid href with ui-router?