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

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside