Issue with saving and restoring filter state for Angular Smart table dropdown filters is not working correctly

After carefully following the guidelines provided in the documentation for persisting the filter state, I encountered an issue. Despite successfully restoring the table state, including the filters, upon reloading the page, the <select> box appears empty, although the filter functionality is still operational.

Fortunately, the text filter continues to function effectively.

Version Information: Angular 1.4.7 Smart-table 2.1.5

You can access the Plunker example through the following link: https://embed.plnkr.co/fK6WfZSZrgSeIG732R2X/

.directive('stPersist', function() {
  return {
    require: '^stTable',
    link: function(scope, element, attr, ctrl) {
      var nameSpace = attr.stPersist;

      //save the table state every time it changes
      scope.$watch(function() {
        return ctrl.tableState();
      }, function(newValue, oldValue) {
        if (newValue !== oldValue) {
          localStorage.setItem(nameSpace, JSON.stringify(newValue));
        }
      }, true);

      //fetch the table state when the directive is loaded
      if (localStorage.getItem(nameSpace)) {
        var savedState = JSON.parse(localStorage.getItem(nameSpace));
        var tableState = ctrl.tableState();

        angular.extend(tableState, savedState);
        ctrl.pipe();

      }

    }
  };
});;

Answer №1

To enhance the Select statement, I suggest incorporating the ngSelected attribute:

<select st-search="category" st-input-event="change" class="input-sm form-control">
    <option value="">All</option>
    <option data-ng-repeat="category in categories" ng-selected="category.id == selectedCategory" value="{{category.id}}">{{category.name}}</option>
</select>

Additionally, you can access the category value from storage as shown below:

//retrieve the table state upon directive loading
if (localStorage.getItem(nameSpace)) {
    var savedState = JSON.parse(localStorage.getItem(nameSpace));
    var tableState = ctrl.tableState();

    // extract category filter (excluding 'All' selection)
    scope.selectedCategory = savedState.search.predicateObject.category || "";

    angular.extend(tableState, savedState);
    ctrl.pipe();
}

To gain insight into the data persistence process and the logic behind 'savedState.search.predicateObject.category', you can include the following JS snippet:

console.log(JSON.stringify(savedState));

https://plnkr.co/edit/bMbIVJ8OkEnfoYbWidu3?p=preview

Answer №2

Here is my approach to solving the issue: I dynamically create a property in the scope with the suffix "_SelectedValue" for each property of the search.predicateObject. This allows each control to easily bind to it in the HTML.

      <select data-st-search="AbiSearch" data-st-input-event="change">
        <option value="">All</option>
        <option data-ng-repeat="row in rowCollection | unique:'AbiSearch' | orderBy: 'AbiSearch'"
                data-ng-selected="row.AbiSearch == AbiSearch_SelectedValue"
                value="{{row.AbiSearch}}">{{row.AbiSearch}}</option>
      </select>

JavaScript:

  if ($localStorage[nameSpace]) {
    var savedState = $localStorage[nameSpace];
    var tableState = ctrl.tableState();

    for (var propertyName in savedState.search.predicateObject) {
      if (savedState.search.predicateObject.hasOwnProperty(propertyName)) {
        scope[propertyName + "_SelectedValue"] = savedState.search.predicateObject[propertyName] || "";
      }
    }

    angular.extend(tableState, savedState);
    ctrl.pipe();
  }

Answer №3

A more efficient solution is available when dealing with multiple tables on the same page that share the same filter name. This approach avoids creating numerous objects to independently store each property.

Here is an example of the HTML code:

      <select data-st-search="Enabled" data-st-input-event="change">
        <option value="">All</option>
        <option data-ng-repeat="row in rowCollection | unique:'Enabled' | orderBy: 'Enabled'"
                data-ng-selected="row.Enabled.toString() == {{StPersistName}}.Enabled_SelectedValue"
                value="{{row.Enabled}}">{{row.Enabled}}</option>
      </select>

And here is the corresponding JavaScript code:

  // Retrieve the table state upon directive initialization
  if ($localStorage[nameSpace]) {
    var savedState = $localStorage[nameSpace];
    var tableState = ctrl.tableState();

    // Check if the object is initialized
    if (!angular.isDefined(scope[nameSpace])) {scope[nameSpace] = {};}

    // Necessary for preselecting the filter in a dropdown menu
    for (var propertyName in savedState.search.predicateObject) { 
      if (savedState.search.predicateObject.hasOwnProperty(propertyName)) {
        scope[nameSpace][propertyName + "_SelectedValue"] = savedState.search.predicateObject[propertyName] || "";
      }
    }

    angular.extend(tableState, savedState);
    ctrl.pipe();
  }

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

Selecting middleware to be executed based on Express JS request parameters

Can someone please advise me on how to select between two distinct middleware functions, based on the request for a specific endpoint? It may involve something along these lines: router.post("/findAvailableAgents", chooseMiddleware(middleware1, ...

Ways to choose an option from a drop-down menu without the select tag using Selenium

I'm looking to perform automated testing with Selenium using Java but I'm facing an issue when trying to select an item from a dropdown list. The HTML structure does not include a select tag for the drop-down menu items (such as Auth ID and Corre ...

the ReactJS data length is accessible when saving changes, but not when refreshing the browser

I am facing a puzzling issue with my API data in this React component. When I console.log the array of 10 objects from the API, everything seems fine. However, when I try to access "data.data.length" and save the file, it works without any errors displayin ...

When a new ajax function is added, the original Ajax code stops functioning

I've been working on getting the code below to function properly. It seems that when I test the code, two validation functions are working correctly. However, when I include the validateUsername() function along with the if statement in the code, ever ...

Utilizing ActivatedRoute in conjunction with another Service

I am facing an issue while trying to utilize the ActivatedRoute service in a different service. The problem lies in the fact that when I use the ActivatedRoute service in my service, it is observing the main App component and not picking up any route param ...

Disabling the shadow when setting the face color in Three.js

When creating geometric objects in my project, I am randomly setting colors on the faces: // Material used to create the mesh var material = new THREE.MeshLambertMaterial({ color: 0xffffff, ambient: 0xffffff, vertexColors: THREE.FaceColors}) function ad ...

Don't waste time creating multiple popups for changing content - streamline your process

Challenge I've successfully extracted information from an array and displayed it dynamically in a tooltip/popup window above each photo on the page. However, with 56 different individuals at various locations, arranging them neatly in a grid poses a ...

The NextJs image entered into an endless loop, throwing an error message that said: "The 'url' parameter is correct, but the response from the

I have been using next/image component with next js version ^12.2.3-canary.17 for my current project. The issue I am encountering is that some images are missing from the source directory, resulting in infinite error logs like the one shown below: https:/ ...

Step-by-step guide on entering text into a hidden field with Selenium WebDriver and Java

I am currently utilizing WebDriver in conjunction with Java for automated testing. I have come across a hidden input field within the following HTML code: <input type="hidden" value="" name="body" id=":6b"> My challenge lies in trying to input data ...

The implementation of Axios cancel token failed to function properly in a real-time search feature within a React application

I'm currently developing a dynamic search feature using React, where users can input search terms and receive JSON results. I attempted to implement axios cancel token for this functionality, but it doesn't seem to be working properly and I' ...

Retrieve a JSON array using an HTTP Get request in JavaScript (with jQuery)

I’ve been experimenting with various code snippets in an attempt to reach my objective, but so far I haven’t found a solution. Objective: My goal is to retrieve a JSON array of objects from a specific web URL using the GET method. This task needs to b ...

Is there a way to retrieve the form name within my directive?

In my code, I am able to retrieve the ngModel name, but now I am looking for a way to also capture the form's name that contains the element with the "validacion" directive. It is crucial for me to programmatically obtain the form's name where t ...

Sliding carousel from right to left

I'm currently working on setting up a slick carousel to continuously scroll, but I need it to move in the opposite direction. Despite trying to add the RTL option, I couldn't get it to work as intended. Check out my Fiddle here (currently scroll ...

Using React Native to trigger a function based on a conditional statement

<Pressable onPress={()=> { if(newID) { EditPress(newID) } else { AddPress } }} style={styles.logBox} > <Text style={{ textAlign:"center", ...

What's the best way to capture an element screenshot using JavaScript?

I'm working on developing a unique gradient selection application. One of the exciting features I would like to incorporate is the ability for users to save their chosen gradients as digital images (.jpg format) directly onto their computers. When the ...

I'm baffled as to why this code isn't functioning properly

My current script seems to be malfunctioning for some reason. I'm using a combination of express, socket.io, jade, and node.js in this setup. Below is the script I am working with: var socket = io.connect(); function addMessage(msg) { var currentDa ...

Utilizing Nested Click Events in jQuery to Enhance User Interaction

I'm really struggling with this and can't seem to find a solution anywhere. I want to capture data when button A is clicked, and then submit that data via AJAX when button B is clicked. Here's what I've been considering: $(document).o ...

Challenge with the Nested List Weight Sum algorithm

Trying to crack the challenge "Nested List Weight Sum": Challenge: If given the list [[1,1],2,[1,1]], the expected output is 10. (four 1's at depth 2, one 2 at depth 1) Here's my approach. function calculateDepthSum(nestedList, sum=0, dept ...

I'm unsure of my recollection on how to utilize the /* syntax in JavaScript

Hey there, I'm facing a little issue. Can someone remind me how to correctly use the /* in JavaScript when dealing with URLs? For instance: if(URL == "www.thing.com/"){} I can't quite remember where to insert the /* so that it applies not just ...

Utilizing regular expressions on a URI parameter in JavaScript

I implemented an ajax function that retrieves three images (PORTRAIT, SQUARE, and LANDSCAPE) from a JSON response: $.ajax({ url: link, method: 'GET', headers: { "Authorization": authToken ...