Search code examples
javascriptangularjsangularjs-ng-repeatng-options

Ng-options dropdown concat fields if the second one is not empty


I have a table users, every user has a username, but there is also a nullable displayname in the table. I want to show al users in a dropdown with their username, and if available also their displayname.

So a user without displayname will be shown like:

<option value="1">*Username*</option>

And a user with displayname will be like:

<option value="1">*Displayname* (*Username*)</option>

My current select is just a regular angular ng-options select.

<select name="Employee" ng-model="selectedUser" ng-options="user.Username for user in unAssignedUsers" required>

I have no clue how I can solve this with ng-options, I've searched everywhere, but I can't find it. Any help would be appreciated!


Solution

  • I would write something like:

    <select name="Employee" 
            ng-model="selectedUser"
            ng-options="selectedUser as combined(selectedUser) for selectedUser in unAssignedUsers" required>
    

    and controller:

    function MyCtrl($scope) {
        $scope.unAssignedUsers = [{
            "Displayname": "GeneralDisplayname",
            "Username": "GeneralUsername"
        }, {
            "Displayname": "SuperDisplayname",
            "Username": "Super"
        }, {
            "Displayname": "",
            "Username": "UsernameTrial"
        }];
        $scope.selectedUser =  $scope.unAssignedUsers[0];
    
        $scope.combined = function(user){
            if(user.Displayname == undefined || user.Displayname == ''){
                return user.Username;
            }
            else {
                return user.Username + " (" + user.Displayname + ")";
            }
        }
    }
    

    Demo Fiddle