Angular - how to avoid adding history when changing search?

I have a property on a page that I would like to reflect by url on a specific page.

I installed reloadOnSearch:false

for this page.

when the page loads it is read local storage

and if this property was stored it will add its value to the search. However, this adds a history entry, so I click back

, I get the url without those search parameters.

I need to avoid double back clicks.

Here is the snippet I made (I will try to run it on plunkr)

my HTML file (snippet.html)

<html ng-app="snippet">
    <head>
        <script src="bower_components/angular/angular.js"></script>
        <script src="bower_components/angular-route/angular-route.js"></script>
        <script src="snippet.js"></script>

    </head>
    <body ng-view="">

    </body>

</html>

      

my JavaScript file (snippet.js)

angular.module('snippet',['ngRoute']).config(function( $routeProvider ){
    $routeProvider.when('/so', {
        'template' : 'this is my template',
        'controller' : 'SnippetCtrl',
        'reloadOnSearch':false
    }).when('/first', {
        'template' : '<a href="snippet.html#/so">go here</a>'
    })
        .otherwise({
        redirectTo : '/first'
        // redirectTo: '/public/session/login'
    });
});


angular.module('snippet').controller('SnippetCtrl', function($location, $scope){

    $scope.name = 'guy';

    $location.search('hello','world')

});

      

  • go to snippet.html
  • the location should change to #/first

  • click link
  • the location should change to #/so

    and then immediately to#/so?hello=world

  • click
  • changing location to #/so

    - I would like to avoid this
+3


source to share


1 answer


After 3 days of trial and error and 10 minutes after I posted this question, I found the answer ...

Instead of using $ location.search (...), I have to do $ location.search (...). replace ()


found my own q / a after 3.5 years. #gottaLoveStackoverflow .. it seems like in later versions of angular I had to split calls.



 $location.search(...)
 $location.replace()

      

Their chain creates an error.
And for the record, according to the angular documentation

When called, all changes to $ location during the current $ digest will overwrite the current history record instead of adding a new one.

Therefore, use with caution.

+6


source







All Articles