Angularjs Select Option Selected Default

38,563

Solution 1

You should NOT use ng-repeat in this way. Please look at ngOptions http://docs.angularjs.org/api/ng.directive:select

Solution 2

I am new to angular and struggled for this a bit. Here is the simple tag that does that , and it is ng-selected:

<option ng-repeat="bank in banks" value="{{bank.id}}" ng-selected="'11' == bank.id" >{{bank.text}}</option>

But again: Dont do it this way as advised by Lander. Rather use ng-options in <select>. Otherwise you will end up with empty first option in the dropdown.assign bank.selected.id in model.(here in your case ng-model is bank.id.)

<select ng-model="bank.selected.id" ng-change="someAngularfunction()" ng-options=" (''+bank.id) as (bank.id +' - '+ bank.text) for bank in banks">
                    <option value="">Select one</option>
</select>

Also remember that the option value will not show the bank-id in the options,rather it will show option value="0" or "1" or "3" which is index. But selected value in dropdown will be bound with bank.selected.id model. For example, if dropdown value is selected as for say bank.id=11 (XX Bank), the bank.selected.id will be set as "11".

Solution 3

I found it, so easy how I did missed that. Here is the correct code.

<div>
<label for="lastname">Bank Name :</label> 
<select ui-select2 ng-model="bank">
    <option></option>
    <option ng-repeat="bank in banks" value="{{bank.id}}">{{bank.text}}</option>
</select>
</div>

$http.get('/AdServerLongTail/api/user').
success(function(data, status, headers, config) {
    if(status == 200){
        $scope.id = (data["id"]);// user id                 
        $scope.bank = (data["bankId"]);                  
    }
}).
error(function(data, status, headers, config) {
    alert("fail");
}); 
Share:
38,563
Yagiz Ozturk
Author by

Yagiz Ozturk

Super fan of C# &amp; JavaScript &amp; Unity.

Updated on July 05, 2022

Comments

  • Yagiz Ozturk
    Yagiz Ozturk almost 2 years

    I started using angularjs in a project. Here i have a quest. I have the below HTML

    <div>
    <label for="lastname">Bank Name :</label> 
    <select ui-select2 ng-model="bank.id">
        <option></option>
        <option ng-repeat="bank in banks" value="{{bank.id}}">{{bank.text}}</option>
    </select>
    </div>
    

    I iterate all the banks to the dropdown. User selects and press SAVE. I correctly got the id and save it to the DB. When the user comes back i could not set the value of the drop down to the one he selected. I do this in the controller.js

    $http.get('/AdServerLongTail/api/user').
    success(function(data, status, headers, config) {
        if(status == 200){
            $scope.id = (data["id"]);// user id                 
            $scope.bank.id = (data["bankId"]);                  
        }
    }).
    error(function(data, status, headers, config) {
        alert("fail");
    }); 
    

    How can I set it to bankID 11 letssay, which is XX Bank?