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?

3
  • You have only submit button in ctrl2? Commented Nov 9, 2016 at 10:46
  • 1
    Probably the most straightforward way is to emit an event on the $rootScope, like answered here 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 stackoverflow.com/a/27410307/3459298 . Commented Nov 9, 2016 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 Commented Nov 9, 2016 at 11:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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");
    };
})

Comments

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>

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.