Retain the dropdown value after the page is refresh or move to another page in angularjs

后端 未结 2 470
礼貌的吻别
礼貌的吻别 2021-01-23 08:46

let me explain my scenario. I am having the dropdownlist in my master page. if changed dropdownlist the data are changed depend upon the dropdownlist value.
If i refreshed m

相关标签:
2条回答
  • 2021-01-23 09:16

    You cannot put an object into the local storage, you must store strings inside local storage.

    If you want, you can have an implementation I did here : How to add local storage in angular?

    For your current code, you don't need to use ng-selected. ng-model is enough.

    <select id="Facility_ID" required typeof="text" 
            name="Facility Name" 
            ng-options="Role.FacilityName for Role in Roles"
            form="DistanceMatrixFormId" 
            class="form-control" 
            ng-model="Role._id"
            ng-change="updateLocalStorage()">
    </select>
    

    And inside your angular controller, what you can do is the following :

    myApp.controller('controllerName', ['$scope', 'LocalStorageService',
         function($scope, LocalStorageService){
    
         // After initialization of your "Role" object
    
         $scope.Role._id = LocalStorageService.retrieve('mySelectValue');
    
         $scope.updateLocalStorage = function(){
             LocalStorageService.store('mySelectValue', $scope.Role._id);
         }
    
    }])
    
    0 讨论(0)
  • 2021-01-23 09:33

    Here is an example that uses a service to store the selected value. Unfortunately the embedded demo does not work because of the sandboxing, but works when served as an application.

    angular.module(
      "App", []
    ).factory("MyStorage", function() {
      const key = "selected";
      return {
        getValue: function() {
          const stored = localStorage.getItem(key);
          return stored ? JSON.parse(stored) : null;
        },
        setValue: function(value) {
          localStorage.setItem(key, JSON.stringify(value));
        }
      };
    }).controller("MyCtrl", function($scope, MyStorage) {
      $scope.options = ["A", "B", "C"];
      $scope.selected = MyStorage.getValue();
      $scope.$watch("selected", newValue => {
        MyStorage.setValue(newValue);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
    <div ng-app="App" ng-controller="MyCtrl">
      <select ng-model="selected" ng-options="x for x in options">
      </select>
    </div>

    0 讨论(0)
提交回复
热议问题