Developer
Developer

Reputation: 1437

how to keep selected option from user when views are changed

Demo:

I have a dropdown, and options are being fecthed from JSON. say

<select ng-model="projectModel" ng-options="project as project.projectName"> 
<option>one</option> 
<option>two</option> 
<option>three</option> 
<option>four</option> 
<option>and so on... </option>
</select>

i have two views page1.html and page2.html

in page1.html i have the following code. select box with above options when ever user select an option say, user has selected three. this has to be saved somewhere. i dont where to save, so next when user clicks page2.html the data selected before in page1.html should not reset.

HTML :

<body ng-app="staticSelect">
  <div ng-controller="ddController">
  <form name="myForm">
    <label for="singleSelect"> Single select: </label><br>
    <select name="singleSelect" ng-model="data.singleSelect">
      <option ng-repeat="x in options">{{x}}</option>
    </select><br>
    <tt>singleSelect = {{data.singleSelect}}</tt>
  </form>
</div>
</body>

JS

app.controller('ddController', ['$scope', function($scope) {
    $scope.data = {
     singleSelect: null,
    };
    $scope.options = ["red","blue","yellow"];
 }]);

 app.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: '01.html',
        controller: 'htmlCtrl',
      })
      .when('/html', {
        templateUrl: '02.html',
        controller: 'htmlCtrl',
      })
 })

any help would be much appreciated! Thanks

Upvotes: 0

Views: 1289

Answers (1)

Sajal
Sajal

Reputation: 4401

Added a reference for 'ng-cookies' in the main view and a service to set and get a cookie.

In Html:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-cookies.js"></script>

The binding html has the method to set the cookie through ng-change

<select name="singleSelect" ng-model="data.singleSelect" ng-change="setSelect()">
   <option ng-repeat="x in options">{{x}}</option>
</select>

You can see the CookieService in the Working Demo

In Controller:

When the setSelect() method is fired the selected value is set in cookie, when the view is returned back to it will re store the value from the cookie

if(cookieService.getAppData("selected") !== null && cookieService.getAppData("selected") !== undefined){
 $scope.data.singleSelect = cookieService.getAppData("selected");
}

$scope.setSelect = function (){
   cookieService.setAppData("selected", $scope.data.singleSelect);
}

Upvotes: 1

Related Questions