Utkarsh Goyal
Utkarsh Goyal

Reputation: 81

To set the values in the select options in angularjs

I have one select option for the drop-down list and two multi-select as well as for the drop-down.

They are getting options from the database and using ng-options for showing the drop-down list.

But I also want to save the static value in these fields.

For that, I have written the code but it's not working:

The codes are:

HTML code:

<div class="form-group" >
    <label class="col-sm-2 control-label">Company: </label>
    <div class="col-sm-10">
    <select  class="form-control m-b"
             ng-model="recom.compName" id ="company"  name="account"
             ng-options = "x as x.compName for x in companyInfo"
             ng-change="onSelect()" required>
    <!-- <option value="">--Select--</option> -->
    </select>
    </div>
    </div>
    <div class="form-group">
    <label style = "position:relative; left:-170px; top:38px">Params:</label>
    <div style = "position: relative; left: 200px; top: 10px">
    <select multiple chosen class="chosen-select"
            ng-model="recom.recoparams" name="account7" id="recoParams"
            tabindex="4" style = "width:880px;"
            ng-options = "y as y.paramName for y in parameters">
        <option value="">--Select--</option>
    </select>
    </div>
    </div>
    <div class="form-group" ng-show="recom.radio=='Demographics'">
        <label style="position: relative; left:7px; top: 8px">Demographics:</label>
        <div style = "position: relative; left:200px; top: -20px">
            <select multiple chosen class="chosen-select" id="demo"
                    ng-model="recom.demo" 
                    ng-options = "z as z.demographicName for z in demotype" 
                    tabindex="4" style = "width:880px;"> 
            </select>

        </div>
    </div>

The controller code is:

$scope.recom.compName = data2[0].compName;// value is coming but its not
                                          // shown in the field in form
$scope.recom.demoName = data2[0].demoName;// value is an array
$scope.recom.paramName = data2[0].paramName;// value is an array

So where I am doing it wrong.

Thanks

Upvotes: 0

Views: 54

Answers (1)

georgeawg
georgeawg

Reputation: 48968

From the Docs:

Complex Models (objects or collections)

By default, ngModel watches the model by reference, not value. This is important to know when binding the select to a model that is an object or a collection.

One issue occurs if you want to preselect an option. For example, if you set the model to an object that is equal to an object in your collection, ngOptions won't be able to set the selection, because the objects are not identical. So by default, you should always reference the item in your collection for preselections, e.g.: $scope.selected = $scope.collection[3].

For more information, see

Upvotes: 1

Related Questions