Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Smart table filter state save dropdown doesn't restore properly

I have followed the instructions in the documentation regarding persisting the filter state. (http://plnkr.co/edit/ekwiNt?p=preview)

When re-loading the page, the table state (including filters) is restored, however the <select> box appears blank, even though the filter does work.

The text filter works fine.

Angular 1.4.7 Smart-table 2.1.5

Here is the plunker 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();

      }

    }
  };
});;
like image 857
darkbluesun Avatar asked Feb 26 '26 16:02

darkbluesun


1 Answers

I would add in the ngSelected attribute in the Select statement:

<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>

and retrieve the category value from storage:

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

    // retrieve category filter (Note: it won't be present when 'All' is selected)
    scope.selectedCategory = savedState.search.predicateObject.category || "";

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

If you want to visualise how the data is persisted (and how I came up with 'savedState.search.predicateObject.category') then add in the following JS to the above:

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

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

like image 186
K Scandrett Avatar answered Feb 28 '26 06:02

K Scandrett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!