0

I have select with existing options, I need to bind values from select to my model.

What I do:

<select ng-model="site.id">
    <option value="1">First<option>
    <option value="2">Second<option>
</select>

Where my model is: user = ['name':'andry', 'site': {'id': 1, name: 'First'}]

I want to bind this select with my model. How is it possible? Currently after choosing value from select site id will be updated, but site name - not.

I'm newbie in angular.

2

3 Answers 3

1

Please, for working with select, use ng-options:

View:

  <body ng-controller="MainCtrl">
    <h1>Select something below</h1>
    <select id="s1" ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
    <h3>The selected item:</h3>
    <pre>{{selectedItem}}</pre>
  </body>

Controller:

  $scope.items = [
    { id: 1, name: 'foo' },
    { id: 2, name: 'bar' },
    { id: 3, name: 'blah' }
  ];

And see next Plunker

$scope.selectedItem contain full object from $scope.items array.

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

Comments

1

Use option with ng-repeat is also fine:

Assign model and value be object

<select ng-model="site">
    <option ng-repeat="item in items" value="{{item}}" 
            ng-selected="site === item">{{item.name}}<option>
</select>

1 Comment

Accepted answer looks more angularish. and I have prerendered options from server-side.
0

You can use $watch function from angular

$scope.$watch("site.id", function(){
 var new_id = $scope.site.id;
 // so you now new id change site name
 $scope.site.name = "asdfasdfasdf"
});

Read this

7 Comments

Thanks for your answers, one more question: how to get value from choosen option?
you can do it by access $scope, like in answer
options are pre-rendered from server-side, not with angular, is it possible to get options from select?
@FUserThrowError, please, add check on not 'undefined' for site.id in watcher :)
@FUserThrowError, Not exactly, what I'm looking for.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.