Search code examples
jquerygridster

save state of added widgets


How do I save the state of the added widget: Below is the function I'm using to add a widget on click of button:

 $('.js-resize-random').on('click', function() {
    gridster.add_widget('<li class="new">The new widget...</li>', 2, 1);
});

Here is the html:

<div>
<button class="js-resize-random">Add widget</button></div>

On refresh I need the added widget to retain its state. How do i do that? Any ideas?????

Thanks in advance!


Solution

  • I made a directive recently for saving and loading the position of a widget of a dashboard. It's a simple attribute of the div of the widget.

    appControl.directive('saveLoadGridsterPosition', ['whateverStoringDependency', function($whateverStoringDependency)
    {
        return function(scope, element, attrs) {
    
            var objectLoaded = whateverStoringDependency.load(attrs.saveLoadGridsterPosition);
            // Empty or errorous load
            if ((objectLoaded == undefined ) || (objectLoaded == null )) {
                console.log('Error loading ' + attrs.saveLoadGridsterPosition+'\'s position.');
            }
            else {
                // Here you set the row/col somewhere in the scope, for me its like scope.widget.row
                scope.widget.row = objectLoaded.row;
                scope.widget.col = objectLoaded.col;
            }
    
            var save = function() {
                // Here you should get the row/col from the scope
                var r = scope.widget.row;
                var c = scope.widget.col;
                var savingObject = {row: r, col: c};
                whateverStoringDependency.save(attrs.saveLoadGridsterPosition, savingObject);
            }
    
            scope.$on('$destroy', save);
        }
    }]);
    

    'whateverStoringDependency' can be a custom service that saves/loads stuff from local storage, cookies, or session. And then I use it like this:

    <div gridster="gridsterOpts">
        <ul>
            <li ng-repeat="widget in widgets" gridster-item row="widget.row" col="widget.col" size-x="widget.sizeX" size-y="widget.sizeY">
                <div data-widget="widget" save-load-gridster-position="{{widget.name}}"></div>
            </li>
        </ul>
    </div>
    

    Maybe it's not nice, but for me it works perfectly. It also can do it on any angular event, like you define "savePositions" and listen for that instead of "$destroy". Hope it helps!