0

I am working on angularjs , Where I need to set selected item by name in selected item.

How DO i do that . I can set item by index but how do i do with itemname

Eg : on load I am setting 1st item as selected item

$scope.internalRoles = data;
                $scope.internalItemSelected = $scope.internalRoles[0];

and Data is like

 data = [{id : 1 , roleName : "admin"}
,{id : 2 , roleName : "superadmin"}]

Now I want to set selected item on basis on roleName

$scope.internalItemSelected =  $scope.internalRoles["superadmin"] ;//based on roleName

But its not working.

How do i set it by name ?

2 Answers 2

1

You can write a extension for your array:

Array.prototype.findItem = function (searchFor) {    
    return this.find(function(item){
       return item['roleName'] === searchFor;
    });
};

Then call it with:

$scope.internalItemSelected =  $scope.internalRoles.findItem("superadmin");

You can also pass 'roleName' as a property of extension to make it more general in use.

Sign up to request clarification or add additional context in comments.

Comments

0

Hi if u wants to set name from the selected item then directly do like this

$scope.internalRoles = data;
  $scope.internalItemSelected = $scope.internalRoles[0].roleName;
  console.log($scope.internalItemSelected);

1 Comment

my dropdown has both Id as well as rolename ... but I want to set selected item programtically by rolename.. So is there any way i can loop through main data source with rolename and set matching rolename .. item to selected

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.