(GMT -12:00) Eniwetok, Kwaja...">

Angularjs sets the selected value

In the html page I have a choice as shown below

<select> <option value="GMT-12:00">(GMT -12:00) Eniwetok, Kwajalein</option> <option value="GMT-11:00">(GMT -11:00) Midway Island, Samoa</option> <option value="GMT-10:00">(GMT -10:00) Hawaii</option> <option value="GMT-9:00">(GMT -9:00) Alaska</option> ... </select> 

Then I request the REST API and get personal data like

 person : { language : "en_US", timezone : "GMT-9:00" ... } 

Question: How can I set "(GMT -9: 00) Alaska" as the one selected when this page is displayed in the AngularJS application?

+4
source share
2 answers

You can use the ng-model attribute to bind the json API response to your select input.

Given your HTML, we get this snapshot of a selection that will be bound to person.timezone .

 <div ng-controller="MainController"> <select ng-model="person.timezone"> <option value="GMT-12:00">(GMT -12:00) Eniwetok, Kwajalein</option> <option value="GMT-11:00">(GMT -11:00) Midway Island, Samoa</option> <option value="GMT-10:00">(GMT -10:00) Hawaii</option> <option value="GMT-9:00">(GMT -9:00) Alaska</option> </select> </div> 

Now you need a controller to actually call the recreation service and get the person object:

 function MainController($scope, $http) { /* query rest api and retrive the person this of course would be replaced with the url of your actual rest call */ $http({method: 'GET', url: 'rest_api_response.json'}).success(function(data, status, headers, config) { $scope.person = data; // dont apply if were in digest if(!$scope.$$phase) $scope.$apply(); }). error(function(data, status, headers, config) { console.log("error retriveing rest api response"); }); } 

For this example, I just made a file called "rest_api_response.json" that contains your answer

 { "language" : "en_US", "timezone" : "GMT-9:00" } 

Heres plunker with a sample containing

+1
source

Your drop-down menu is not in the "Angular world" .
You don't have a model attached to it, so when you change your selection, nothing will really happen in the angular world.

So either:

1. Choose what you drop out to work in the "Angular world" with a binding to the model (and then easily do what you need by assigning the value that you return from the server as the selected value.)
Heres a nice link .

2. Continue to work in a non-Angular world with pure JS or frameworks such as JQuery, and do it differently.

0
source

All Articles