id as ng-model for select in angularjs

2020-08-17 07:25发布

I am not getting the id value of the option value of selected item of tag.

<div ng-controller="UserCreationCtrl">
    <form novalidate="novalidate" class="form-horizontal">
        <div class="control-group">
            <label class="control-label" for="inputFirstName">First name:</label>

            <div class="controls">
                <input type="text" id="inputFirstName" ng-model="doctor.firstName" placeholder="First name"/>
            </div>
        </div>

        <div>
            <span  class="nullable">
                <select ng-model="user.lookupId" ng-options="select as speciality.lookupName for speciality in specialityList" ng-change="selectedSpecilaty()">
                    <option value="">-- choose speciality --</option>
                </select>
            </span>
        </div>
    </form>
</div>

My controller

app.controller('UserCreationCtrl', ['$scope', 
    function ($scope) {

    $scope.specialityList = [
                                 {lookupId : 1, lookupName: 'speciality1'},
                                 {lookupId : 2, lookupName: 'speciality2'},

                                 {lookupId : 4, lookupName: 'speciality6'},
                                 {lookupId : 3, lookupName: 'speciality3'}
                                 ];

    $scope.user = {firstName: 'first name value', lookupId : 4};

    $scope.selectedSpecilaty = function()
    {
        alert($scope.user.lookupId);
    }
}]);    

How can i do this. the alert box displying the value as 'undefined'.

2条回答
一夜七次
2楼-- · 2020-08-17 08:03

You have to change the select key that refers to the value key specified in your ng-options. Since your value key is speciality then to bind user.lookupId to your ng-model with the currently selected option's lookupId, you have to change select to specialty.lookupId

So your select's ng-options should be:

<select ng-model="user.lookupId" ng-options="speciality.lookupId as speciality.lookupName for speciality in specialityList" ng-change="selectedSpecilaty()">
  <option value="">-- choose speciality --</option>
</select>
查看更多
小情绪 Triste *
3楼-- · 2020-08-17 08:16

ng-options patterns can be confusing to get started with, as there are quite a bunch.

What you wrote right now means:

select     as     speciality.lookupName    for   speciality   in   specialityList
 ^-- the value to set to   ^-- what to display      ^-- iteree name  ^-- iterables

So the variables you have available in the expression are everythin you have defined on the scope, and the contextual specialty variable. When you select something it'll assign it to select, which is indeed undefined.

What you're looking for is

ng-options="speciality.lookupId as speciality.lookupName for speciality in specialityList"

This will set the value of what ng-model is pointing to to the contextual specialty's lookupId

查看更多
登录 后发表回答