简体   繁体   中英

how to set the value of an option when using ng-options in a select with angularjs

I have a problem where I need to post the id field of a table to update a foreign-key of a record in the db, but I'm using the ng-options attribute to populate the select's options. I searched online and found that to set the value i had to use ng-model="dataSet.desiredColumnName" to change the value to which ever other column i choose

so I have this piece of html for the select;

<select id="affiliation" ng-model="affiliationTable.affiliation_id" ng-change="alert(jQuery('#affiliation option:selected').val());" name="affiliation" ng-options="row.desc for row in affiliationTable"></select>

the problem is, I want to make a specific option selected depending on which row in my html table is clicked on. the table is defined like this;

<tr ng-repeat="row in tableData">
    <!--{{row.name}}-->
    <td>
        <a href='#' ng-click="invokeModal(row);" id="{{row.id}}">{{row.name}}</a>
    </td>
    <td>{{row.active}}</td>
    <td>{{row.end_date}}</td>
    <td>{{row.start_date}}</td>
</tr>

and invokeModal uses the selected row to determine which option to select in select#affiliation;

$scope.invokeModal = function (row) { //memberDescription
    if(row == undefined){
        //blah blah ...
    }else{
        //blah blah ...
        angular.forEach($scope.affiliationTable, function (affiliation) {
            if (affiliation.id == row.affiliation_id) {
                $scope.affiliationTable.affiliation_id = affiliation.affiliation_id;
            }
        });
    }
        //invokes the modal window that select#affiliation is held within
    jQuery("#mem").modal('show');
};

my problem is that it seems as if it's adding an empty option in the beginning of the select and making that option selected. . .wtf?

I think you ng-option expression needs to be corrected, it should be

row.id as row.desc for row in affiliationTable

The ng-model value on the select should be of same type when you assign the model property from code. You are assigning the id property of table, so on select the model should be updated with id property currently it being set to the full row object.

ng-options="value as label group by groupName for object in lists"

value can be any unique Identifier, label can be any text to display, groupname is the value based on which items need to be grouped and object is an object of the list on which traversing would be done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM