sacan sacan - 6 months ago 11
AngularJS Question

Angular JS Forms submit not sending ID

I am trying to send the course

id
to the controller in a form button, but it does not seem to work. The controller logs the
vm.add.year
correctly but
vm.add.course
gets
undefined
. Why?

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);
};

Answer

I would do the following to fix this:

Add ng-click directive to button:

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

Remove the form action leaving just form:

<form>

Change the function to take a parameter:

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

Change this to initialize vm.add.course as 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>

This follows the patterns found on Angular's site: https://docs.angularjs.org/guide/forms