Abhishek
Abhishek

Reputation: 2019

Render specific element in input from a list - AngularJS

I am rendering select options as follows:

<select ng-model="curUserId" ng-options="u.id as u.name for u in users"></select>  

In Controller code:

$scope.users = [{"id":1, "name":"abc"}, {"id":2, "name":"def"}, ...]  
$scope.curUserId = 2;  //Selected User

This loads select box with user def as selected user as ng-model holds curUserId value.
I need to do the same in input box where I should show selectedUser, one way is to assign a scope variable to input box and then in controller iterate through users list and get selected user.
i.e.

for(var i=0;i<$scope.users.length){
    if($scope.users[i] == $scope.curUserId)
    {
        $scope.selUser = $scope.users[i].name;
        break;
    }
}  

Is there any other way I can get selUser in AngularJS instead of iterating through list.
Thanks!

Upvotes: 0

Views: 162

Answers (1)

Michael Kang
Michael Kang

Reputation: 52837

You can bind to the model instead of the id:

<select ng-model="curUser" ng-options="u as u.name for u in users track by u.id"></select> 

In Controller code:

$scope.users = [{"id":1, "name":"abc"}, {"id":2, "name":"def"}, ...]  
// coming from server
$scope.curUser = {"id":2, "name":"def"};  //Selected User

Upvotes: 1

Related Questions