Alan2
Alan2

Reputation: 24602

How can I use a <select> in AngularJS to select from an array and then store that value in localStorage?

I created the following:

    $scope.option.questionOrderBy = [
    { label: 'PId', key: ['problemId', 'QuestionId'] },
    { label: 'QId', key: 'questionId' },
    { label: 'Modified By', key: 'modifiedBy' },
    { label: 'Modified Date', key: 'modified' },
    { label: 'Status', key: 'questionStatusId' },
    { label: 'Title', key: 'title' }
    ];

and use this here:

    <select
       data-ng-model="option.selectedQuestionSort"
       data-ng-options="o.label for o in option.questionOrderBy">
       <option style="display: none" value="">Select Sort Order</option>
    </select>

and in my HTML:

     data-ng-repeat="row in grid.data | orderBy:option.selectedQuestion.key">

This works but I would like to use local storage to remember the value of the sort.

When I try to store the "option.selectedQuestionSort" this is an array !

Is there a way I could change the above so that I could store a value in localstorage instead of an array for option.selectedQuestionSort. Then when my code starts I could get the value and have the select show the right selection?

Note here's my code to store into local storage:

    $scope.$watch('option.selectedQuestionSort', function () {
        if ($scope.option.selectedQuestionSort != null ) {
            localStorageService.add('selectedQuestionSort', $scope.option.selectedQuestionSort);
        }
    })

The problem is $scope.option.selectedQuestionSort is an array so I don't think I can store that correctly.

Upvotes: 2

Views: 761

Answers (1)

Gilad Peleg
Gilad Peleg

Reputation: 2010

Use JSON.stringify(object) when storing the data( works for objects and arrays, but might fail for items with circular reference, which isn't the case here).

When you want to get the data out, you need to convert it back to an object (or array) format, use JSON.parse(string) which returns the object.

So with your localStorage service is should be:

localStorageService.add('selectedQuestionSort', JSON.stringify($scope.option.selectedQuestionSort));

And when you take it out:

selectedOption = JSON.parse(localStorageService.get('selectedQuestionSort'));

Upvotes: 1

Related Questions