简体   繁体   中英

AngularJs : Multiple clicks on same button is not working

I have created a web page in Angular Js. Whenever I navigate to some other page from Home page and click on Home button from that page it navigates back to Home page which is expected and working fine. But when again I click on Home button then I'm expecting a page refresh (because currently it is Home page) but it is not happening.

Angular does not reload the view when the $location of the route you are trying to go to is the same as the current route you are on. You can use the reload() method to achieve this. See https://docs.angularjs.org/api/ngRoute/service/$route

(Make sure you switch the api version to match the Angular version you are using)

For a cleaner solution (imho) than using search parameters see the following code (I am using controllerAs syntax):

angular.module('app').controller('MainController', [
  '$location',
  '$route',
  function ($location, $route) {
    var main = this;

    main.goToHome = function () {
      if ($location.path() === '/') {
        $route.reload();
      }
    };
  }
]);

in combination with calling that function on your home button link on click:

<a href="#/" ng-click="main.goToHome()">Home</a>

This function checks the location when you click your button, if the location is / then it reloads the view.

Of course you can replace the route url with whatever url you use for your home route.

The following is an untested, alternative solution I came up with.

In your routes configuration object for the home page (which I am assuming has a url of /home ), specify the following parameters:

{
    // ...
    reloadOnSearch: true,
    redirectTo: function (routeParams, path, search) {
         if (search.redirected) {
             // don't redirect, so return same path + search
             return '/home?redirected=true';
         } else {
             return '/home';
    },
    // ...
}

The thinking is that when you link to /home , the redirectTo() function will fire and redirect you to /home?redirected=true . That will be a change to the search parameter, so the route should reload correctly due to specifying reloadOnSearch: true . Since the home page links will always be pointing to /home , the page should always reload.

It's a bit ugly, and will likely cause the home page controller to run twice when going from some other page back to the home page, but if you can't get any other way to work, this one might be worth a try.

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