Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 611
Jason van der Zeeuw Avatar asked Nov 22 '25 11:11

Jason van der Zeeuw


1 Answers

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

like image 178
Maxim Shoustin Avatar answered Nov 24 '25 01:11

Maxim Shoustin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!