Angular JS Forms提交不发送ID

时间:2016-05-26 08:51:59

标签: angularjs forms form-submit

我正在尝试通过表单按钮将课程id发送到控制器,但它似乎不起作用。控制器正确记录vm.add.yearvm.add.course获取undefined。为什么?

index.html:

    <form method="post" ng-submit="vm.addCourseToYear()">
        <table class="table">

            <tr ng-repeat="course in vm.courses | filter:search">
                <td>{{course.courseName}}</td>

                <td><select id="addCourse" name="addCourse" class="form-control"  ng-model="vm.add.year" required>
                    <option value="year1"> Year1 </option>
                </select></td>

                <td><input style="display:none" ng-value="course._id" ng-model="vm.add.course">
                    <button type="submit" class="btn btn-primary" id="{{course._id}}">Add</button>
                </td>
            </tr>
         </table>
    </form>

index.controller.js

function addCourseToYear(){
    console.log(vm.add.course);
    console.log(vm.add.year);
};

3 个答案:

答案 0 :(得分:0)

尝试将代码更改为:

<form method="post" ng-submit="vm.addCourseToYear(vm.add.course._id)">

希望这能解决你的问题...... :)

答案 1 :(得分:0)

display:none从中移除对象, 将其更改为visibility: hidden;position:absolute

<input style="visibility:hidden;position:absolute;" ng-value="course._id" ng-model="vm.add.course">

答案 2 :(得分:0)

我会做以下事情来解决这个问题:

将ng-click指令添加到按钮:

<button type="submit"
        class="btn btn-primary"
        ng-click="vm.addCourseToYear(vm.add)"
        id="{{course._id}}">Add</button>

删除表单操作,只留下表单:

<form>

更改函数以获取参数:

function addCourseToYear(newItem){
    console.log(newItem.course);
    console.log(newItem.year);
};

更改此项以将vm.add.course初始化为course._id:

<td>
    <input style="display:none" ng-init="vm.add.course = course._id" ng-model="vm.add.course">
    <button type="submit" class="btn btn-primary" id="{{course._id}}">Add</button>
</td>

这遵循Angular网站上的模式:https://docs.angularjs.org/guide/forms