In my AngularJS application, I have a situation where I am nesting forms inside an ng-repeat. The issue arises when a button within the repeat triggers a function that includes a $scope.$broadcast. While everything else in the function executes correctly, the broadcast ends up triggering multiple times - once for each item in the ng-repeat.
Unfortunately, moving the button outside of the ng-repeat is not an option as it would result in loss of form and data references. I have created a demonstration on Plunker showcasing this setup. If you input values in one of the inputs and click "next" while monitoring the console, you will observe the broadcast firing multiple times. My goal is to find a solution where the broadcast only fires once while still having access to the form for validation checks as shown in the demo code.
Below is the JavaScript code excerpt, and the rest can be found on the Plunker:
(function () {
var app = angular.module('App', []),
/** manually triggers $validate event to validate the given form */
isFormValid = function ($scope, ngForm) {
var i = null;
//$scope.$emit('$validate');
$scope.$broadcast('$validate');
if(! ngForm.$invalid) {
return true;
} else {
// make the form fields '$dirty' so that the validation messages would be shown
ngForm.$dirty = true;
for(i in ngForm) {
if(ngForm[i] && ngForm[i].hasOwnProperty && ngForm[i].hasOwnProperty('$dirty')) { // TODO: is 'field.$invalid' test required?
ngForm[i].$dirty = true;
}
}
}
};
app.controller('appCtrl', ['$scope', function ($scope) {
$scope.wizardStep = 1;
$scope.nextStep = function () {
var ngForm = $scope['stepForm_' + $scope.wizardStep];
if(isFormValid($scope, ngForm)) { // trigger manual validation
$scope.wizardStep++;
}
};
$scope.prevStep = function () {
$scope.wizardStep--;
};
$scope.submit = function () {
var ngForm = $scope['stepForm_' + $scope.wizardStep]; // we can make this line common
if(isFormValid($scope, ngForm)) {
alert('Form is valid. Submitting...');
}
};
}]);
})();
I welcome any suggestions or assistance on how to address this issue. I understand that certain elements like inline styles in the HTML are not recommended practices, but they were included in the Plunker for expediency.
Thank you in advance.