uladzimir
uladzimir

Reputation: 5689

How to bind select with existing model

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.

Upvotes: 0

Views: 141

Answers (3)

Chen-Tsu Lin
Chen-Tsu Lin

Reputation: 23234

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>

Upvotes: 1

Artyom Pranovich
Artyom Pranovich

Reputation: 6962

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.

Upvotes: 1

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3645

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

Upvotes: 0

Related Questions