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>
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With