Last Updated: February 25, 2016
·
2.993K
· 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>

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

Angular apps often share the page with analytics and payment scripts that are not Angular modules. Those scripts execute on the same origin as the framework.

Security insights from Cside