I have nested forms in an ng-repeat with a button whose click event calls a function that does a couple of things including a $scope.$broadcast. Everything in the function triggers once except for the broadcast which triggers on per item in the ng-repeat.
I cannot move the button outside the repeat or I lose the form and data references. I have a demo plunker that shows the basic setup. If you enter values into one of the inputs and click next while monitoring the console and you should see the broadcast fire multiple times (once per ng-repeat item). What I need is a way to have the broadcast only fire once while still maintaining the reference to the form for validation checking as per the demo code.
Here is the JS and the rest is in 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...');
}
};
}]);
})();
Any help or ideas are greatly appreciated and I know things like styles in the html and other aspects of the demo code are no-no's. I just did those to get the plunkr up faster.
TIA