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.

uladzimir
  • 5,639
  • 6
  • 31
  • 50
  • Why would not you use ng-options? http://stackoverflow.com/questions/13047923/working-with-ng-options-in-angular http://docs.angularjs.org/api/ng.directive:select – Artyom Pranovich Feb 12 '14 at 09:06
  • @ArtyomPranovich, actually, options rendered from server-side, so they are predefined. Is there way, how to get options from select? – uladzimir Feb 12 '14 at 09:09

3 Answers3

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.

Artyom Pranovich
  • 6,814
  • 8
  • 41
  • 60
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>
Community
  • 1
  • 1
Chen-Tsu Lin
  • 22,876
  • 16
  • 53
  • 63
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

Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37