ng-click不适用于锚元素

时间:2014-05-14 06:48:07

标签: javascript angularjs twitter-bootstrap-3

Q1:我尝试在 bootstrap 中使用导航制作导航栏并绑定 ng-click 对锚点。 但是after I click锚链接,没有任何事情发生。

Q2:我注意到anchor link clicked won't be active by setting bg-color了吗?如何实施?

这是JSfiddle ...

<div ng-controller="SuiteSectionCtrl">
<ul class="nav nav-pills nav-stacked">
    <li class="active"><a href="#">All Suites</a>
    </li>
    <li><a ng-click="handleClick">Suite1</a>
    </li>
    <li><a href="#">Suite2</a>
    </li>
    <li><a href="#">Suite3</a>
    </li>
</ul>

3 个答案:

答案 0 :(得分:2)

缺少函数调用的括号。你应该:

ng-click="handleClick()"

答案 1 :(得分:0)

回答Q2:

也许有更智能的解决方案,但这个解决方案也适用:

angular.module('myApp').controller('MenuCtrl', ['$scope', '$location', '$rootScope',
    function ($scope, $location, $rootScope) {
        $rootScope.$on('$locationChangeSuccess', function () {
            var path = $location.path();
            // you may apply logic on the path (group together in case of dropdown-menu e.g.)
            $scope.topMenu = path;
        });
    }
]);
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation"
     ng-controller="MenuCtrl">
    <div class="container-fluid">
        <div class="navbar-header">
            <!-- ... -->
        </div>

        <div class="navbar-collapse collapse" id="navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                <li ng-class="{active: topMenu == '/'}">
                    <a href="#">Home</a></li>
                <li ng-class="{active: topMenu == '/about'}">
                    <a href="#about">About</a></li>
                <!-- more... -->
            </ul>
        </div>
    </div>
</div>

答案 2 :(得分:0)

我已更新您的代码。将ng-app directive添加到您的body代码中。并在您的html更改ng-click="handleClick"ng-click="handleClick()"

<body ng-app="app"><div ng-controller="SuiteSectionCtrl">
    <ul class="nav nav-pills nav-stacked">
        <li class="active"><a href="#">All Suites</a>
        </li>
        <li><a ng-click="handleClick()">Suite1</a>
        </li>
        <li><a href="#">Suite2</a>
        </li>
        <li><a href="#">Suite3</a>
        </li>
    </ul>
    </div></body>

我们的JS代码是

var executionAPP = angular.module('app',[])//register your app 
executionAPP.controller('SuiteSectionCtrl',['$scope',function($scope){

    $scope.oneAtATime = true;

    $scope.testSuites = [{title:"TestSuite1",content:"TestContent1"},
                         {title:"TestSuite2",content:"TestContent2"},
                         {title:"TestSuite3",content:"TestContent3"},
                         {title:"TestSuite4",content:"TestContent4"},
                         {title:"TestSuite5",content:"TestContent5"}];
    $scope.handleClick = function(){
        alert('Accordion clicked');
    };

}]);

Updated Fiddle...