Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent search changes from spamming history

I'm using links like #!/OrderList?id=123, which shows the list of all orders and more details of the order 123. With reloadOnSearch=false and watching $routeUpdate it works fine, except for one thing: All such links get put into the browsers history, while I'd prefer to have only one such link there. For example, instead of

#!/OrderList?id=123
#!/OrderList?id=124
#!/OrderList?id=125
#!/AnotherList?id=678
#!/AnotherList?id=679

just the last member of each group, i.e.,

#!/OrderList?id=125
#!/AnotherList?id=679

I'm aware of $location.replace(), but I can't see where to place it when the change happens via following a link. I tried to place it in $scope.$on("$routeUpdate", ...), but it did nothing, probably because it's too late when the route has already changed.

I'm not using neither router-ui nor the HTML5 mode (just plain angular-route).


I'm afraid, I wasn't clear about me insisting on using href rather than a custom handler. I want the links to work with middle mouse click and bookmarks and everything. A combination of ng-href and ng-click might do what I want, but I've found a simple solution working with plain links.

like image 803
maaartinus Avatar asked Sep 01 '16 20:09

maaartinus


1 Answers

Looks like you may want to update the URL query parameter using an ng-click function instead of relying on a link, then call a function like the one below to update the parameter... With replace state, the history should only track the current value. I haven't tested this case so if you try it, let me know if it works.

        function changeUrlParam (param, value) {
            var currentURL = window.location.href;
            var urlObject = currentURL.split('?');
            var newQueryString = '?';

            value = encodeURIComponent(value);

            if(urlObject.length > 1){
                var queries = urlObject[1].split('&');

                var updatedExistingParam = false;
                for (i = 0; i < queries.length; i++){
                    var queryItem = queries[i].split('=');

                    if(queryItem.length > 1){
                         if(queryItem[0] == param){
                            newQueryString += queryItem[0] + '=' + value + '&';
                            updatedExistingParam = true;
                         }else{
                            newQueryString += queryItem[0] + '=' + queryItem[1] + '&';
                         }
                    }
                }
                if(!updatedExistingParam){
                    newQueryString += param + '=' + value + '&';
                }
            }else{
                newQueryString += param + '=' + value + '&';
            }
            window.history.replaceState('', '', urlObject[0] + newQueryString.slice(0, -1));
        }
like image 119
Philip Rittenhouse Jr. Avatar answered Nov 09 '22 06:11

Philip Rittenhouse Jr.