[フレーム]
Last Updated: February 25, 2016
·
2.585K
· felipebrnd

Angular: how to update model with single object properties

Problem: You have a collection of objects which are used to build a select and you want to bind the selected option to a single property.

TL;DR; Solution: use ng-repeat + ng-value to build the select.


Details:

ng-value attribute receives an angular expression which will be used to bind ng-model. I tried using ng-options but only worked for me when using ng-repeat.

Controller code:

app.controller('CWExampleController',function(){
 //collection:
 this.persons = [{name:'Mike',id:1},{name:'Molly',id:2}];

 //ng-model property:
 this.personId = null;
})

HTML :

<div ng-controller="CWExampleController as ctrl">
 <select ng-model="ctrl.personId" ng-value="p.id">
 <option ng-repeat="p in ctrl.persons" value="{{p.id}}">{{p.name}}</option>
 </select>
 <p>Selected person id: {{ctrl.personId}}</p>
</div>

AltStyle によって変換されたページ (->オリジナル) /