html - 使用angularjs laravel在存储在数据库中的选择框中显示所选项目

标签 html angularjs laravel angularjs-ng-options angularjs-ng-model

我试图从数据库中获取一个存储值到一个选择框中,但它没有显示。所选值显示在控制台(检查元素)中,但它只是不显示。

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()

检查元素( Chrome )

enter image description here

从 inspect elements 可以清楚地看到数据在那里,但它只是没有显示为选择框中的选定项。请有人告诉我我做错了什么。

最佳答案

您的 ng-options 表达式与您需要的不匹配。您在语法中有 track by employee.usersId employee.employeeName for employee in employeesName track by employee.usersId,这意味着您需要将 ng-model 设置为 userId而不是名称,也作为对象而不仅仅是字符串,即您的 ng-model 理想情况下应该是 schedule.employee = {usersId:'someid'} 作为默认选择。现在来看你的情况,看起来你正在尝试将 ng-model 设置为一个字符串并且你想要它是员工的名字(这可能是一个糟糕的选择,因为你已经有一个 id)你应该尝试使用替代语法select as label for value in array` :

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

还请记住,当您使用 select as 语法时,您应该删除 track by,因为它们不是为协同工作而设计的。

旁注:-

使用ng-init 是个坏主意用于初始化 ng 模式。医生说:

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.

关于html - 使用angularjs laravel在存储在数据库中的选择框中显示所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27651200/

相关文章:

php - 解析错误 : syntax error, 意外 '?' in/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 233 - laravel

java - 使用 Jsoup 替换标签内的文本

javascript - AngularJS - 如何验证元素指令?

javascript - 使用 AngularJS 循环 JSON 文件时 "Not well-formed"firefox 错误

php - laravel model save() 将重复的数据保存在数据库中

php - 拉维尔 8 : Weird missing required parameter

javascript - jquery 验证插件 ajax 提交不工作

JavaScript - 暂时暂停页面滚动但保持滚动条滚动直到取消暂停

javascript - 如何在 HTML5 Video 元素上获取视频的 FrameRate

angularjs - 带有闭包的 AngularJS 示例