AngularJS: Eliminate an item from the location.search

Although there are many similar questions on SO, none of the answers have been able to help me so far.

After poring over the Angular $window and $location documentation, I am still struggling to achieve my desired outcome in my client app.

Consider a webpage where users can set multiple filters and share them. Sharing is done through GET parameters like ?f=AN_HASH, which triggers a query to retrieve the matching filter set from the server.

The active filters are stored in SessionStorage using $sessionStorage from ngStorage.

At some point, the user should be able to clear the current filter set by clicking a button. The expected action triggered by this button should:

  • Clear the Session Storage item
  • Clear the specific url query parameter ?f= (without affecting other parameters that may be added in the future)
  • Reload the page

This is the function called on ng-click:

$scope.clearFilters = function(){

    $sessionStorage.queryFilters = {} // Empty SessionStorage
    $scope.activeFilters = false      // Disable Clear button

    console.log('before:', location.search)

    // $location.search({})
    // $location.search('f', null)
    // $location.search('f', null).replace()

    console.log('after:', location.search)

    $window.location.reload() // reload the page
}

Between the two console.log statements, you can see what I've attempted so far. The logs display the following:

before: ?f=THE_HASH
after: ?f=THE_HASH

It appears that nothing has changed (even the GET query in the address bar remains).

I also tried simply emptying the location.search object like this:

$scope.clearFilters = function(){

    $sessionStorage.queryFilters = {} // Empty SessionStorage
    $scope.activeFilters = false      // Disable Clear button
    location.search = ''              // Reset location.search and reload page
}

While this method worked, I'm not entirely satisfied with it as it removes ALL elements from the GET query, potentially causing issues in the future if additional parameters must be preserved.


For further insight into my search efforts, please see:

  • This question;
  • This discussion.


Following @Chris's suggestion, I attempted to run:
angular.element(document.body).injector().get('$location').search("f",null)

However, the URL GET parameter remained unaffected. In the attached image, you can view my findings from the Chrome console.

https://i.sstatic.net/XDnOB.png

Answer №1

Changing URL parameters in Plunker and Jsbin can sometimes cause issues. Here is the code snippet that you can easily copy and paste into a local file for testing.

<html lang="en" ng-app="myApp">
    <head>
      <base href="/">
      <meta charset="utf-8">
      <title>AngularJS Example</title>
      <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular.min.js"></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular-route.min.js"></script>
    </head>

    <body>
      <div ng-controller="myCtrl">
        <button ng-click="setFilter()">Set Filter</button>
        <button ng-click="clearFilterValue()">Clear Value</button>
        <button ng-click="clearEntireFilter()">Clear Entire Filter</button>
      </div>
    </body>

    <script>'use strict';

angular.module('myApp', ['ngRoute']).config(
    ['$locationProvider', function ($locationProvider) {

  $locationProvider.html5Mode(true).hashPrefix('');
}]);

angular.module('myApp').controller('myCtrl', 
    ['$scope', '$location', '$window', 
    function ($scope, $location, $window) {

  $scope.setFilter = function () {
    $location.search('f', 'something');
    $window.location.reload();
  }

  $scope.clearEntireFilter = function () {
    $location.search('f', null);
    $window.location.reload();
  }

  $scope.clearFilterValue = function () {
    $location.search('f', '');
    $window.location.reload();
  }
}]);


    </script>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Empty req.body in Express JS is not fulfilling the necessary data requirements

I've been racking my brain for hours trying to figure out why req.body is showing up empty. I've scoured every corner of stackoverflow and tried every solution that I could find, but nothing seems to be working. Express.js POST req.body empty ...

I encountered an unexpected JSON.parse error while working with perfectly valid JSON data

I have encountered an issue while parsing JSON data. Despite running the JSON through JSONLint and receiving a green label confirming its validity, I am still unable to parse it using my Angular Controller. The JSON code can be accessed here. Here is the ...

Using node.js to import functions from another file

The code below is what I currently have: // app.js var exports = module.exports = {}; module.exports = function () { var exported = {}; .. exported.myFunction = function (data, callback) { .. } . ...

How can I transform an HTML div into a video file like MP4 using Python and Django?

I'm looking to take a HTML page and target a specific <div> within it in order to convert it into video format. Purpose: I understand that HTML is typically static, but I have a requirement to transform it into a video. I'm seeking method ...

Stop ui-router from transitioning based on an HTTP query

Is there a way to prevent a state change for a specific "to" state in ui-router without using onEnter? Let's consider the following route: .state('auth.confirm', { url: '/confirm/:resetToken', template: '<confirm-page& ...

Load Bootstrap tab activation

I'm having trouble getting the active class to work on my tabs. I've tried using body onload click trigger, showing tabs by ID, and many other methods, but nothing seems to be working. I have implemented hashed URLs to allow for individual tab li ...

triggering two separate functions with ng-click

I'm attempting to trigger two separate functions with the ng-click event, using ng-click="Reset();Search()". Unfortunately, it doesn't seem to be working as expected. Can anyone confirm if this is the correct approach for calling multiple functio ...

HTML code featuring multiple dropdown menus, each equipped with its own toggleable textarea

I have multiple HTML drop downs, each triggering a textarea based on the selection. Currently, I'm using show and hide JavaScript functions for each question individually. Is there a way to streamline this so that I don't have to write separate c ...

Create a video file using binary data obtained from a socket connection

I have successfully created a socket connection and am sending binary stream data to the server. On the server side, I am receiving the binary data and now I want to use this data to create a video file and save it on the server. However, I am struggling t ...

How to stop Accordion from automatically collapsing when clicking on AccordionDetails in Material-UI

I am working on a React web project with two identical menus. To achieve this, I created a component for the menu and rendered it twice in the App component. For the menu design, I opted to use the Material UI Accordion. However, I encountered an issue wh ...

What is the best way to set the input type file to null when deleting an image in Vue?

My form allows users to upload an image, and everything was functioning properly until I encountered an issue. When I remove an image and try to upload the same image again, the @change function is not triggered. I am unable to reset the file value to null ...

jQuery causing trouble with AJAX in Rails

Currently, I am fetching a list of users from the controller side and generating the HTML code to append it. This is how I wrote the code: $.ajax({ type : "get", contentType : "application/json; charset=utf-8", url : "/users/sear ...

How to access the ckeditor function within a dialog HTML element without relying on the "onOk" event

I'm in the process of developing my own plugin and dialog using an html element. I have a requirement where upon clicking the html element, I need to add some text to the editor. However, I'm facing challenges with the onOk function and finding i ...

utilizing the variables provided by the factory to modify the content

I'm trying to wrap my head around how this factory works. Can I interact with the variables like save, drop, update in a way such as this? <a href="" ng-click="drop()">X</a>. Or is there something else that needs to be done for it to work ...

What is the most effective way to find the nearest ID?

Within an iOS app, there exists a webView that contains numerous lines of text. Currently, I am utilizing JavaScript to identify which specific text line has been clicked by the user. However, due to varying line heights and line breaks resulting in blank ...

JavaScript adding arrays to JSON files

At this point, I feel like I have no other option. Everything appears to be correct from my perspective. However, nothing seems to be working. I decided to create a small food app for myself to keep track of what I'm eating. I set up a JSON file name ...

Using jQuery, identify when a key has been pressed within a three.js environment

How can I detect a keypress within a designated scene contained in a div with the id "world"? I've written the following code in an attempt to achieve this, but it doesn't seem to be working properly. Here is the code snippet: $('world&apos ...

What could be causing TypeORM skip() and take() function to not function properly?

I have encountered a database issue with the Delivery table, which contains more than 4 million rows in MySQL. The following function, adminDeliveriesViewCount, is intended to count the total number of deliveries, but it's not functioning as expect ...

Using JSON with Google Chart Tools

When referring to this example at , it is noted that the method data.addRows() requires a list of lists. A URI (/data/mydata.json) can be accessed to retrieve the following data: [["Canada", 66], ["Turkey", 10], ["Hungary", 23], ["Italy", 49]] Despite a ...

Sending parameters to a service's factory

Here is the HTML code I am working with: <div class='container-fluid' ng-controller="TypeaheadCtrl"> <p></p> <b>Selected User</b> Enter a name: <input type="text" ng-model="selected" typeahead="user ...