简体   繁体   中英

angularjs: ng-click on <a> not working, works on <button>

Here is the Javascript

    function gotoUrl($scope, $location, $http, $window) {
      $scope.setRoute = function (route) {
        $location.path(route);
    };

My code is

      <ul class="nav navbar-nav navbar">
            <li><a href="#" data-ng-click="setRoute('summary')"><span
                    class="icon-bar-chart"></span> Summary</a></li>
            <li><a href="#
            " data-ng-click="setRoute('transactions')"><span
                    class="icon-reorder"></span>
                Transactions</a></li>
            <li><a href="#" data-ng-click="setRoute('budgets')"><span
                    class="icon-calendar"></span>
                Budgets</a></li>
        </ul>

The routes are configured as

app.config(function ($routeProvider) {
    $routeProvider
        .when('/summary', {templateUrl: '../static/partials/summary.html', controller: 'SummaryController'})
        .when('/transactions', { templateUrl: '../static/partials/listTransaction.html', controller: 'TransactionsManagerController'})
        .when('/profile', {templateUrl: '../static/partials/profile.html', controller: 'ProfileController'})
        .when('/new', {templateUrl: '../static/partials/addTransaction.html', controller: 'TransactionAddController'})
        .when('/budgets', {templateUrl: '../static/partials/budgets.html'})
        .otherwise({redirectTo: '/summary'});
});

When I click on Transactions , it takes me to Summary

When I change the code from <a> to <button> , it works, what is that I am doing wrong here?

http://docs.angularjs.org/api/ng.directive:a

Modifies the default behavior of the html A tag so that the default action is prevented when the href attribute is empty .

Try setting href="" instead of href="#" . If you are using hashbang mode routing, the latter results in a full-page reload, which is what seems to be happening in your case as well. Any link with href="#" that you click will cause your app to fully reload the page and load the default route -- in your case Summary .

You can get rid of gotoUrl function and modify DOM to

<a href="#/transactions"><span></span>Transactions</a>

AngularJS will take care of the rest.

change this code segment

<li><a href="#
        " data-ng-click="setRoute('transactions')"><span
                class="icon-reorder"></span>
            Transactions</a></li>

to

<li><a href="/transactions"><span
                class="icon-reorder"></span>
            Transactions</a></li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM