Reputation: 2550
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 ?
Upvotes: 0
Views: 40
Reputation: 1705
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.
Upvotes: 1
Reputation: 2962
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);
Upvotes: 0