Here’s an Angular feature that’s incredibly useful for handling events triggered by an input element inside a ng-repeat.
Gathering input from a user from an radio button inside an ng-repeat has its difficulties, and there’s hardly any documentation for it. So I’ve broken it down here, and wanted to share it with y’all. The key is to be able to access the variable created in the ng-repeat from your template (i.e. report in the ng-repeat 'report in allReports' from the example below)?
<table> <tbody> <tr ng-repeat="report in allReports"> <td class="text-right"> <input type="radio" name="report" ng-model="$parent.report" id="report_{{$index}}" ng-value="{{report}}"/> </td> <td>{{ report.DateTime | date : 'MMM d, y h:mm:ss a' }} </td> </tr> </tbody> </table> <div class="modal-footer"> <button class="btn btn-primary" ng-click="selectReport()" translate="Continue"></button> </div>
The first thing we need to do is assign ng-model to the $parent
object. In our case it would be $parent.report
and assign it a name attribute. We also want to assign that variable name (i.e. report
) to ng-value.
In our controller then, the contents of this variable are accessible by name. In our case we can gather the data of this particular report
with $scope.report
.
// Controller.js // Get the report from the selection and do something with it. function allReportSelectionController($scope) { $scope.allReports = data; // Assume this is data with a lot of reports $scope.selectReport = function () { var timeStamp = $scope.report.timeStamp,// Here we are accessing the data from the selected input element id = $scope.report.id; xhrFunction.getSpecificReport(id, timeStamp).then(//Do Something); } }
Hope that helps! Let me know if you have any questions! Thank you.