Search code examples
htmlangularjslaravelangularjs-ng-optionsangularjs-ng-model

Display selected items in select box that is stored in database using angularjs laravel


I am trying to get a stored value from the database into a select box, but it is not displaying. The selected value shows in the console(inspect element) but it's just not displaying.

HTML

<td data-ng-class="{'has-error': employeeSchedule.employee.$invalid && employeeSchedule.employee.$dirty}">
    <select class="form-control input-sm" name="employee" ng-model="schedule.employee" ng-init="schedule.employee='{{$schedules[0]->employee}}'" ng-options="employee.employeeName for employee in employeesName track by employee.usersId">
        <option value="">Select Employee</option>
    </select>
</td>

ANGULARJS

app.controller('UpdateWorkScheduleCtrl', [ '$scope', '$http', function ($scope, $http)
{
    $http.get('/schedule/employees').success(function(employeedata) {
        $scope.employeesName = employeedata;
    });
}]);

CONTROLLER(LARAVEL)

public function getEmployees() {

    $users = DB::select(DB::raw("SELECT `usersId`, CONCAT(`firstName`,' ',`middleName`,' ',`lastName`) AS employeeName 
                                 FROM `users` 
                                 WHERE `userStatus` != 'Administrator' 
                                 AND `userStatus` != 'Director' 
                                 AND `userStatus` != 'HR Specialist'"));

    return Response::json($users);
} // end function getEmployees()

INSPECT ELEMENTS(CHROME)

enter image description here

It is clear from inspect elements that the data is there, but it is just not being displayed as the selected item in the select box. Can someone show me what I am doing wrong please.


Solution

  • Your ng-options expression does not match with what you need. You have track by employee.usersId in the syntax employee.employeeName for employee in employeesName track by employee.usersId, Which means that you would need to set ng-model to userId instead of name and also as an object not just as string, i.e your ng-model should ideally be schedule.employee = {usersId:'someid'} for default selection. Now coming to your case which pretty seems like you are trying to set ng-model as a string and you want it the name of the employee (Which probably is a poor choice since you already have an id) you should try the alternate syntax with select as label for value in array`:

    ng-options="employee.employeeName as employee.employeeName for employee in employeesName "
    

    Also remember when you use select as syntax you should remove track by, as they are not designed to work together.

    Side Note:-

    It is a bad idea to use ng-init for initializing ng-mode. And doc says:

    The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.