2

I am trying to bind a select list to ng-model state abbreviation value.. for instance "AK" for Alaska. The initial selection doesn't work apparently because the ng-model is set to a string instead of an object. I've looked all over and there are all other people that have this issue but I haven't found a solution that works.

my controller has the following code

  $scope.states =
            [
            {
                "name": "Alabama",
                "abbreviation": "AL"
            },
            {
                "name": "Alaska",
                "abbreviation": "AK"
            },
            {
                "name": "Arizona",
                "abbreviation": "AZ"
            }];

  //I want the model to be the abbreviation string
  $scope.state = "AK";

Here is the markup

<select class="form-control m-b" data-placeholder="Select Location" 
required=""  ng-model="state" 
ng-options="state as state.name for state in states track by state.abbreviation">
                            </select>

    <p>Selected State {{state}}!</p>

Here is a plnkr that shows shat I'm talking about

https://plnkr.co/edit/IzDY4GrOxJSaMV2MMP30

1 Answer 1

2

You can use

$scope.state.abbreviation

to get the abrevation of the state object that's selected.

plkr solution

OR

you could change the ng-options to

ng-options="state.abbreviation as state.name for state in states track by state.abbreviation"

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that second option is what I was looking for, the model is now the abbreviation. Thank You! I still have a problem where the initial selection isn't set to "Alaska". I created this plnkr... plnkr.co/edit/OC2DVIlOmpHw75I9ERI8
The problem with doing something like that is that the ng-model needs to be set to an object in the list of ng-options to set it from the controller. Is there a reason you can't do something like this plkr?
No, there isn't a reason that I can't do it. I was just hoping to only work with the abbreviations and not have to lookup the object from the abbreviation. I was hoping that with ng-model being set properly that it could be bound to the abbreviation initially.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.