Is it possible to concatenate values in Angular ng-options

AngularjsAngularjs Ng-Options

Angularjs Problem Overview


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>

Angularjs Solutions


Solution 1 - Angularjs

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>

Solution 2 - Angularjs

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.

Solution 3 - Angularjs

try this instead

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrickCurlView Question on Stackoverflow
Solution 1 - AngularjsboatcoderView Answer on Stackoverflow
Solution 2 - AngularjsMistalisView Answer on Stackoverflow
Solution 3 - AngularjsDipali JadhavView Answer on Stackoverflow