Manish Kumar
Manish Kumar

Reputation: 10512

Submit form manually in angularJS

I have this angular form

  <ion-nav-buttons side="right">
    <a class="button button-icon icon ion-android-done" href="#search/search-form" ng-click="submitNewPublishMessage(msgForm.$valid, msgForm)"></a>
  </ion-nav-buttons>
  <ion-content> 
      <form name="msgForm" class="css-form" novalidate>   
        <input type="text" name="title" ng-model="msgForm.title" ng-minlength="10" ng-maxlength="150" required>
        ...
        ...

I want to manually submit form when i click a by calling submitNewPublishMessage() Inside controller both msgForm.$valid, msgForm is coming undefined.

$scope.submitNewPublishMessage = function(isValid, form)
{
  alert(isValid);
  alert(JSON.stringify(form));
}

Upvotes: 0

Views: 513

Answers (2)

JB Nizet
JB Nizet

Reputation: 692231

I don't know about ionic, but my guess is that the ionContent directive has its own scope, and that the form is thus created in this inner scope, rather than the scope of the controller.

As always, the trick is to avoid storing things directly in the scope, but rather to store them as attributes of an object of the scope.

So, in the controller, add the following line of code:

$scope.forms = {
};

$scope.model = {
};

And in the view, use

<ion-nav-buttons side="right">
  <a class="button button-icon icon ion-android-done" href="" ng-click="submitNewPublishMessage(forms.msgForm)"></a>
</ion-nav-buttons>
<ion-content> 
  <form name="forms.msgForm" class="css-form" novalidate>   
    <input type="text" name="title" ng-model="model.title" ng-minlength="10" ng-maxlength="150" required>

Note that the above

  • doesn't pass the msgForm.$valid flag in addition to the msgForm, since it is redundant
  • doesn't store the model of the form (i.e. the values entered in the form fields) in the NgFormController itself. Doing so would cause a conflict between the input widget and the input model.

I would really, really avoid using links to submit forms, if I were you. Links are meant for navigation, not for form submissions. Use a button.

Upvotes: 1

Kashif Mustafa
Kashif Mustafa

Reputation: 1182

Put ng-click event inside form like

    <form name="msgForm" class="css-form" novalidate>
         <ion-nav-buttons side="right">
        <a class="button button-icon icon ion-android-done" href="#search/search-form" ng-click="submitNewPublishMessage(msgForm.$valid, msgForm)"></a>
      </ion-nav-buttons>
      <ion-content> 

            <input type="text" name="title" ng-model="msgForm.title" ng-minlength="10" ng-maxlength="150" required>
            ...
            ...
</form>

Upvotes: 0

Related Questions