-1

I want to submit multiple forms from different controllers but I'm not sure how. The reason for this is because I have a save button on multiple different tabs of my webpage. By clicking save I want to submit the form and then validate it. I want to submit my forms from main controller and I don't know how to refer to the forms.

This is my form

<form name="vm.driverForm" novalidate>
    <formly-form class="top20" model="vm.model" fields="vm.fields" options="vm.options" form="vm.driverForm"></formly-form>
</form>

and submit function in my main controller

vm.onSubmit = onSubmit;
function onSubmit() {
    $scope.vm.driverForm.$setSubmitted();  //THIS IS THE PART I'M TRYING TO FIGURE OUT
}

and the button in the main controller

<button type="button" ng-click="vm.onSubmit()" class="btn btn-primary submit-button top5">Save Driver</button>

I don't want to copy and paste my submit function and save button code into every single controller that uses the button.

  • do you mean this by vm? if it is the case then you should remove the $scope from your js file and vm from the html – nour Mar 16 '18 at 16:34
  • vm.driverForm is not part of the same controller where the function lives. That's why I've been trying to use $scope.vm.driverForm – dsafas fsafasfsa Mar 16 '18 at 16:37
  • or how can I check if form on controller X is valid from controller Y? – dsafas fsafasfsa Mar 16 '18 at 16:44
  • @nour, 'vm' means view-model. You can use controllerAs property to alias $ctrl as anything, say vm. Now you could do vm.popertyname instead of $ctrl.propertyname. – Satish Kumar Mar 16 '18 at 22:02

1 Answers1

1

Use Services.

Say you created a service, EventService.

Whenever you want to submit the form from another controller, emit an event.

EventService.$emit("submit-event");

Add a listener to that event in your main controller, which will execute the onSubmit function.

EventService.$on("submit-event", vm.onSubmit);


Note 1: Service class must extend the EventEmitter class

Note 2: Both the controller must use a common service to emit and listen the event.


Can one controller call another?

Satish Kumar
  • 601
  • 6
  • 14