0

I want to make an item is pre selected in my selectbox,how it is possible in angularjs my code is given below

<select  ng-model="selectedClient"  ng-init="client.id == 117" ng-options="client.name for client in 
                         clients" class="form-control"></select>

I want to make item 117 as preselected but it is not working.

1
  • it should be ng-options="client.id as client.name for client in clients" Commented Mar 11, 2015 at 13:09

3 Answers 3

1

Do not think AngularJS models as only values or ids if you have Arrays filled up objects. You have to approach it as object in this situation.

If you have an array like this:

var clients = [{
    id: 1,
    name: "Client 1",
    active: false
}, {
    id: 2,
    name: "Client 2",
    active: false
}, {
    id: 3,
    name: "Client 3",
    active: false
}];

You can preselect one of them like below:

$scope.selectedClient = clients[0];

Keep in mind that the selectedClient is an object.

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

3 Comments

here clients[0] means first item from clients,rite? In my case I am not sure in which item should be select? I have 'Id' value,can I select by using id value?
You have to find proper object which has the id value that you have. I use findWhere method of the underscorejs.org for my that like needs. For example: $scope.selectedClient = _.findWhere(clients, {id: 1});
returning undefined :(
1

You assign the selected item to the model object selectedClient

$scope.selectedClient = $scope.clients[1]

Demo: Fiddle

3 Comments

I want to select based on condition
@ShihabudheenMuhammed yes... based on the condition you assign the object to selectedClient
Thank you for the answer,now it is working but the problem is now value of selectedClient is integer rather than object. I want to object there.. :(
0

Your mark up should look like below.

HTML

<select  ng-model="selectedClient" ng-options="client.id as client.name for client in clients" 
class="form-control" ng-init="selectedClient = 117"></select>

1 Comment

when using client_id as it returns client_id,I want to client object,how it is possible?

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.