简体   繁体   中英

Prevent page refresh when clicking a link in AngularJS

I've found a weird behavior in AngularJS when clicking links. My goal would be to prevent the page to refresh when the path is the same, and only the query string changes.

The strange thing is that this happens already... but only sometimes. At least in my particular scenario, some links trigger the page refresh, and some others simply not, even when they look the same (except minor changes like ones having a title attribute and others not).

<a class="btn btn-primary" ng-href="https://.../search?_target=event&...>Edit</a>

Besides this odd thing, which perhaps is the result of me doing something wrong, I would like to ask for the common way of avoiding page refresh on link clicks, and if possible when someone manually changes the URL, but only the query string. It's annoying to have to wait for the whole app to load just because you wanted to activate some particular pop-up, for instance.

Note that I have the HTML5 mode enabled.

Thanks.

It looks like you're using absolute links in your <a> tags.

You should use your router's links (if you're using ui-router it's ui-sref to navigate state).

[EDIT] The problem seems to be a lot different, so here's another wording:

"I need to display a popup based on my state params in all of my states, whenever my state changes".

So here's how to do it:

The logic says that since you have to display this in all of your state changes, you should hook a $stateChangeSuccess function ( docs ).

That way, you can implement your logic there and display pop-ups and everything. I suggest you put this into your app.js file or if the app is relatively large in some events.js file or whatever you prefer

angular.module('your_app_name').run(function($rootScope){
    $rootScope.$on('$stateChangeSuccess', 
        function(event, toState, toParams, fromState, fromParams){
            // you have your toParams, your toState and everything here, so use your logic to open your popup window.
    })
});

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