Is it possible to concatenate values in Angular ng-options
Asked Answered
A

3

76

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>
Augustine answered 20/11, 2013 at 16:44 Comment(3)
I have done this before and it does work. My syntax s.subsidiary.sid._value_ as s.subsidiary.subsidiary_no._value_ + ' :' + s.subsidiary.subsidiary_name._value_ for s in subsidiaries. The only difference I can see is that I did not use parentheses. Try removing them and see if it works.Shakiashaking
Another option would be to create a property called full_name with the concatenated value before binding the data.Shakiashaking
okay the problem was the double quotes, needed single.Augustine
S
140

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>
Spleen answered 7/6, 2014 at 15:29 Comment(5)
I added this answer to remove the question from the list of unanswered AngularJS questions.Spleen
Just a note about something that tripped me up: The quotes are important. It won't work with double quotes inside double quotes or single quotes inside single quotes.Electrum
Absolutely dbl quotes inside dbl quotes don't work, because they end the current string and start another one. You have to mix up the quotes like above.Spleen
Instead of this use like (b.first_name +'&nbsp;'+ b.last_name). This will work.Bronze
for me, 'b.id as (b.first_name + b.last_name) for b in buyers' has perfectly worked.Wineskin
P
4

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.

Polychaete answered 24/4, 2017 at 13:31 Comment(0)
O
0

try this instead

<select ng-model="buyers" ng-options="b as (b.first_name + " " + b.last_name) for b in buyers">
</select>
Op answered 16/2, 2021 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.