angularjsdrop-down-menung-optionsng-submit

Select element value not being sent with other form elements in Angular


I am using Angular to submit the contents of a form to an API endpoint. Everything worked fine until I tried to change one of the text input fields to a select dropdown. I am using ng-options to populate the select drop down but when I go to send the form contents to the API endpoint the value of the select element is not sent. Below is the HTML (with class and styling information removed for brevity) and the Angular.

HTML

<form ng-submit="self.addNewEmployee()" novalidate>
    <input ng-model="self.form.employeeName" type="text">
    <select ng-model="self.form.department" ng-options="dept.name as dept.Name for dept in self.departmentList">
    </select>
    <input ng-model="self.form.salary" type="text" />
    <input id="btnSubmit" type="submit" value="Add Employee" />
</form>

Angular

<script type="text/javascript">
    var adminToolApp = angular.module('adminToolApp', []);

    adminToolApp .controller('AdminToolController', function ($scope, $http) {
        var self = this;
        self.departmentList = [];

        // Gets all departments to populate select input
        $http({
            method: 'GET',
            url: 'https://api.myServer.net/api/getAllDepartments',
            headers : {
                'Content-Type': 'application/json',
            }
        }).then(function(result) {
            self.departmentList = result.data;
        }, function (error) {
            console.log(error);
        });

        // Submits form data to add new employee
        self.addNewEmployee = function() {
            return $http({
                method: 'POST',
                url: 'https://api.myServer.net/api/addNewEmployee',
                data: angular.toJson(self.form),
                headers: {
                    'Content-Type': 'application/json',
                }
            }).then(_submissionSuccess, _submissionFailure);
        };

        // Private methods

        function _submissionSuccess(response) {
            self.submissionResults = response.data;
        };

        function _submissionFailure(response) {
            self.submissionResults = 'An error occured: ' + response.status;
        };
    });
    </script>

When I inspect the payload sent to the API two of the form elements are present (employeeName and salary) however department is not present. I defined self.form.department as the ng-model for the select element, why is it not submitted as part of the form collection?


Solution

  • Try change this

     ng-options="dept.Name as dept.Name for dept in self.departmentList">