0

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!

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Problem is that curUser value is sent from server and value is not an object.
Use "track by" then, for object equality

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.