0

I have an object inside a select ng-options, but i need to select the second one, how can i do that?

here is a example:

http://plnkr.co/edit/NTdaDNFFbbDlu7fJOeDK

$scope.prop = [
    {t: "Service 1", j:"oi1"},
    {t: "Service 2", j:"oi2"},
    {t: "Service 3", j:"oi3"},
] ;

$scope.prop.value.j = "oi2";

2 Answers 2

1

First, your ng-model attribute should be different from select options array, in this case, let's rename it to selected_value. Then, in your controller, you can assign it with the second option from $scope.prop

$scope.prop = [
    {t: "Service 1", j:"oi1"},
    {t: "Service 2", j:"oi2"},
    {t: "Service 3", j:"oi3"},
] ;


$scope.selected_value = $scope.prop[2]

Then in your select html.

  <select ng-model="prop.selected_value" ng-options="v.j for v in prop">
  </select>
Sign up to request clarification or add additional context in comments.

3 Comments

How can I use using a string like: "oi2" $scope.selected_value,j = "oi2"
$scope.selected_value.j = "oi2", you can do that.
@PedroMarques you first need to assign selected_value and then trying to modify his 'j' value. Check it plnkr.co/edit/mKJTEDRphSIlOrYoxcIH?p=preview
0

First of all, you need to set your value.j to an empty String in your controller, because you don't need to do this in controller.

$scope.prop.value.j = "";

Then, in the following code, add ng-init: (the code comes from your posted Plunker link, and I just added the ng-init directive to select the index of 1 (2nd entry in the array)

<select ng-init="prop.value = prop.value || prop[1]" ng-model="prop.value" ng-options="v.j for v in prop">

3 Comments

this is not elegant solution. why use ng-init, just initialize within controller.
Assuming the OP just knows the index he/she wants to select, without having to know the content of the selection, because the data may come from a dynamic service layer that has different content for the second element in the data array.
you can do it from controller.

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.