Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to concatenate values in Angular ng-options

Basically, I'm trying to populate a select box but concatenate values from the first_name column and last_name column.

What I want to do (doesn't work):

<select ng-model="buyers" ng-options="b.id as (b.first_name + " " + b.last_name) for b in buyers"></select> 

What does work:

<select ng-model="buyers" ng-options="b.id as b.first_name for b in buyers"></select> 
like image 289
PatrickCurl Avatar asked Nov 20 '13 16:11

PatrickCurl


People also ask

How do ng-options work?

Definition and Usage. The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.

What is Ng option?

The ng-options Directive in AngularJS is used to build and bind HTML elements with options to a model property. It is used to specify <options> in a <select> list. It is designed specifically to populate the items on a dropdown list. This directive implements an array, in order to fill the dropdown list.


2 Answers

The quotes are important. It won't work with double quotes inside double quotes or single quotes inside single quotes.

What does work:

<select ng-model="buyers" ng-options='b.id as (b.first_name + " " + b.last_name) for b in buyers'></select> 
like image 66
boatcoder Avatar answered Oct 12 '22 13:10

boatcoder


You can concatenate a string using this synthax:

ng-options="i.x + ' ' + i.y for i in items" 

The following snippet concatenate firstname and lastname:

angular.module('myApp', []);    function MyCtrl($scope) {    $scope.names = [{firstname: 'Jon', lastname: 'Snow'},                    {firstname: 'Rob', lastname: 'Stark'},                    {firstname: 'Ned', lastname: 'Stark'}];  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>    <div ng-app="myApp" ng-controller="MyCtrl">    <select ng-model="selected" ng-options="n.firstname + ' ' + n.lastname for n in names"></select>    selected: {{selected}}  </div>

Note that parenthesis are not required, but it may improve readability.

like image 42
Mistalis Avatar answered Oct 12 '22 12:10

Mistalis