检索存储在db中的值,并使用angularjs和laravel显示在选择框中

时间:2014-12-30 00:09:06

标签: angularjs laravel

我正在尝试检索存储在MySQL数据库中的值,并显示数据库中的选定值以及其他选择框项,以便可以更新它们。 我遇到的问题是选择框没有显示存储在数据库中的选定值,而是默认为空的第一个选项。我正在使用angularjs从laravel中检索值:

laravel

public function getEmployeeshifts() {
    $employeeShift = DB::table('shift')
                       ->select('shiftId', 'title')
                       ->get();

    return Response::json($employeeShift);
}

angularjs

$http.get('/schedule/employeeshifts').success(function(shiftdata) {
    $scope.employeeshifts = shiftdata;
});

HTML

<select class="form-control input-sm" name="employeeshift"
                                      ng-model="time.employeeshift"
                                      ng-init="time.employeeshift='{{$schedules[0]->title}}'" 
                                      ng-options="employeeshift.title for employeeshift in employeeshifts track by employeeshift.shiftId" required>
        <option value="">Select</option>
</select>

所需的输出

<option value="101">Shift A</option>
<option value="102">Shift B</option>
<option value="103">Shift C</option>

基于上面的期望的输出我实际想要存储在数据库中的是值,但我需要向用户显示这些单词。我不确定我做错了什么,因此我要求帮助解决这个问题。

2 个答案:

答案 0 :(得分:0)

AngularJS会根据ng-model的值自动解析选择的项目。您似乎将time.employeeshift的值设置为title值,而不是shiftId值。尝试将ng-init属性更改为time.employeeshift='{{$schedules[0]->id}}'或等效。

答案 1 :(得分:0)

您必须将模型设置为所需的选定项目。在您的情况下,您没有在ng-init中正确设置。您应该使用employeeshift作为您的模型。

<select ng-model="employeeshift"
        ng-init="employeeshift = employeeshifts[0]" 
        ng-options="employeeshift.title for employeeshift in employeeshifts">
        <option value="">Select</option>
</select>

这会将选定的班次对象绑定到$scope.employeeshift变量,并将默认值设置为employeeshifts数组中的第一个对象