Search code examples
javascriptangularjscordovaangular-controller

Submit form and cordova functions are not getting called


When I try to call the ng-submit - submitForm() function, I am unable to call the function and it doesn't do anything. How do I resolve it?

(function () {
  'use strict';

  /**
   * @ngdoc function
   * @name app.controller:MainCtrl
   * @description
   * # MainCtrl
   * Controller of the app
   */
  angular.module('app')
    .controller('MainCtrl', ['$scope', 'cordova', function ($scope, cordova) {
      console.log("Hello...");
      cordova.ready.then(function () {
            alert('Cordova is ready');
            console.log("Ready....");
      });
      // function to submit the form after all validation has occurred            
      this.submitForm = function() {
        console.log("Submit form...");
        // check to make sure the form is completely valid
        if ($scope.userForm.$valid) {
            alert('our form is amazing');
            console.log("For submitted..")
        }
      };
  }]); 
  
})();


Solution

  • Note: I will presume the cordova.ready is working but it will only be resolved when your app is running either in an emulator or in a physical device.

    I suggest to check if cordova is ready inside the this.submitForm method.

    (function () {
      'use strict';
    
      angular.module('app')
        .controller('MainCtrl', ['$scope', 'cordova', function ($scope, cordova) {
          console.log("Hello...");
    
          // function to submit the form after all validation has occurred            
          this.submitForm = function() {
            console.log("Submit form...");
            cordova.ready.then(function () {
                alert('Cordova is ready');
                console.log("Ready....");
                validateAndSendForm();
            }, function() {
                console.log('It is not cordova, decide to send or not the form.');
                // validateAndSendForm();
            });
          };
          function validateAndSendForm() {
            // check to make sure the form is completely valid
            if ($scope.userForm.$valid) {
                alert('our form is amazing');
                console.log("For submitted..")
            }
          }
      }]); 
    
    })();
    

    Your html should looks something like:

    <div ng-controller="MainCtrl as main">
      <form method="post" ng-submit="main.submitForm()">
        <!-- More fields here -->
        <button type="submit">Submit</button>
      </form>
    </div>