Edward
Edward

Reputation: 929

Angularjs set the selected value

In html page I have a select like 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 query the REST API and get a person data, like,

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

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

Upvotes: 4

Views: 9918

Answers (2)

Amir Popovich
Amir Popovich

Reputation: 29836

Your drop down isn't in the "Angular world".
You have no model that is binded to it so when you change your selection nothing will really happen in the angular world.

So either:

1.Change you drop down to work in the "Angular world" with model binding(and then easily perform what you need by assigning the value you get back from the server as the selected value.)
Heres a nice reference.

2.Continue working in the non-Angular world with pure JS or frameworks like JQuery and do it differently.

Upvotes: 0

ug_
ug_

Reputation: 11440

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

Given your HTML we get this select drop down that will bind 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 the controller to actually call the rest 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 sample I just made a file called "rest_api_response.json" that contains your reponse

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

Heres a plunker with the sample contained

Upvotes: 1

Related Questions