0
<div ng-controller="ctrl1">
    <form name="form1" ng-submit="submitForm()">
        <input type="text" name="email" />
    </form>
</div>

<div ng-controller="ctrl2">
    <button> Submit </button>
</div>

Here from ctrl2, I want to trigger form submit action for a form which is in ctrl1

How to achieve this in angularJs?

Sangram Jagtap
  • 79
  • 1
  • 2
  • 7
  • You have only submit button in ctrl2? – Natiq Nov 09 '16 at 10:46
  • 1
    Probably the most straightforward way is to emit an event on the $rootScope, like answered here http://stackoverflow.com/a/19498009/3459298 . If you want to avoid this, say because you don't want to polute the rootScope or you are worried about performance, maybe you want to choose to implement your event bus as a service, also specified here http://stackoverflow.com/a/27410307/3459298 . – Eduardo Páez Rubio Nov 09 '16 at 10:52
  • This example will surely help you to submit from different controller using $controller service. Check the sample you will get idea...---> [Submit from different controller](http://stackoverflow.com/questions/40477112/ionic-angularjs-calling-methods-via-template-outside-of-controller/40483559#40483559) – Pitchiah Natarajan Nov 09 '16 at 11:13

3 Answers3

0

You could emit an event on the button click and then use rootscope to broadcast it down - ctrl1 could then listen for this an submit the form in response.

theleebriggs
  • 571
  • 2
  • 5
0

You can emit an event from the second controller and listen to it in the first controller.

function CtrlOne($rootScope) 
{
  $rootScope.$on('submitEvent', function(event, args) {
      //submit your form here
  });
}

function CtrlTwo($scope,$rootScope) 
{
  $scope.submit=function(){
    $rootScope.$emit('submitEvent', args);
  }
}
<div ng-controller="CtrlOne">
    <form name="form1" ng-submit="submitForm()">
        <input type="text" name="email" />
    </form>
</div>

<div ng-controller="CtrlTwo">
    <button ng-click="submit()"> Submit </button>
</div>
  • I don't see how this example can work. The two controllers are in different scopes (the events are not going to reach sibling scopes) and also the submit function is not reachable since the controller instance is not published using the `as` syntax. – Eduardo Páez Rubio Nov 09 '16 at 11:02
0

You can achieve using $rootScope or services or event brodcasting

app.controller('ctrl2',['$scope','$rootScope',function($scope,$rootScope) {
    $scope.submitForm = $rootScope.mainSubmit();
}]);

app.run(function($rootScope){
    $rootScope.mainSubmit =function(){
        console.log("hey");
    };
})