0

I have a select option with the options of yes or no.

<select ng-model="selectedAnsw" ng-options="answ.text for answ in answs"></select>

$scope.answs = [
            {
                text: "Yes",
                value: Yes
            },
            {
                text: "No",
                value: no
            } ];

I want to store what the user selects in $scope.selectedAnsw and have it save + populate the select. So if the user selects No and then navigates to a different page and comes back to yes/no page No is preselected because they selected it a bit ago/it was stored. I don't need to keep the selection forever, just during this session. Thinking this might have to do with $rootScope + ng-select.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
RooksStrife
  • 1,647
  • 3
  • 22
  • 54

1 Answers1

0

You can use service to achieve this. Create a service with setter and getter methods. Inject the service in your controller.

Now whenever user selects any option set it in service using setter, and when user comes back to same page, use getter method to get the user selection.

For setting it back to your select box you can take the object from your service and directly assign it to your ng-model.

For e.g

$scope.selectedAnsw = yourServiceValue

Below is simple snippet explaining the use of service.

var app = angular.module("myapp", []);

app.controller("testCntrl", function($scope, storeData) {
  $scope.selectedAnsw = {};

$scope.answs = [
            {
                text: "Yes",
                value: "Yes"
            },
            {
                text: "No",
                value: "no"
            } ];
  
  $scope.getAns = function() {
    $scope.userAns =  storeData.getUserAns();
  }
  
  $scope.setAns = function(ans) {
    storeData.setUserAns(ans);
  }
})
.service("storeData", function(){
  this.setUserAns = function(ans) {
    this.ans = ans;
  }
  
  this.getUserAns = function() {
    return this.ans;
  }
})
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
  <div ng-controller="testCntrl">
<select ng-model="selectedAnsw" ng-options="answ.text for answ in answs" ng-change="setAns(selectedAnsw)">
     <option value="" disabled>Select An Answer</option></select>
</select>
  <div>User Selected : {{selectedAnsw}}</div>
  
  <button ng-click="getAns()">Show user selection</button>
  <div>User had Selected : {{userAns}}</div>
    </div>
  </div>
ExpectoPatronum
  • 507
  • 4
  • 14