Mohammed Al-Hanabi
Mohammed Al-Hanabi

Reputation: 123

what is best practice for Angular drop down menu & ng-option

good day, i created a drop dow menu on AngularJS. but it return to me an object not an item {"deptName":"IT","id":"1"}. i need to return the id only to my table. is there any thing i need to change on ng-options="item.deptName for item in department.departments" see the sample:

JS

angular.module('firstApp', [])

.controller('EmpController', function() {
    var vm = this;
    // define a list of items
    vm.employees = [{
        name: 'Alex',
        id: '2233',
        dept: 'IT'
    }, {
        name: 'Scott',
        id: '2244',
        dept: 'IT'
    }, {
        name: 'Joe',
        id: '2255',
        dept: 'IT'
    }];
})

.controller('DeptController', function() {
    var vm = this;
    vm.departments = [{
        deptName: 'IT',
        id: '1'
    }, {
        deptName: 'Finance',
        id: '2'
    }, {
        deptName: 'Marketing',
        id: '3'
    }];
});

HTML

<div class="jumbotron">


    <h1>The Selected is </h1>
    <h2>{{main.employeeData.dept}}</h2>

    <!-- form to add computer to the list -->
    <form class="form-inline" ng-controller="DeptController as department">
        <div class="form-group">
            <label class="col-sm-2 control-label">Dept menu</label>
            <div class="col-sm-6">
                <!--<select  required="true" ng-model="main.employeeData.dept" ng-options="item.deptName  for item in department.departments">-->
                <!--<option value="">Select Category</option>-->
                <!--</select>-->

                <select required="true" ng-model="main.employeeData.dept" ng-options="item.id as item.deptName for item in department.departments">
                    <option value="">Select Category</option>
                </select>
            </div>
        </div>

    </form>
</div>

</div>

Upvotes: 2

Views: 1242

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

You need to use as of ng-options like item.id as item.deptName .It will show item.deptName on drop-down value & assign item.id value to the respective select ng-model

Markup

 <select required="true" ng-model="main.employeeData.dept" ng-options="item.id as item.deptName for item in department.departments">
      <option value="">Select Category</option>
 </select>

Working Plunkr here

Upvotes: 2

Related Questions