Home > Mobile >  Can't access form from inside AngularJS controller
Can't access form from inside AngularJS controller

Time:10-09

I am trying to manually reset a form from inside an AngularJS controller but I can't access it using either $scope, or using controllerAs. When I log $scope.SupportForm, it returns undefined.

HTML

<form name="supportForm" id="supportForm" novalidate> 
  
    <label for="message">Message</label>
    <textarea name="message" id="message" model="$ctrl.formData.message" maxlength="5000" required></textarea>   

     <button type="submit" data-ng-click="$ctrl.submitForm($ctrl.formData)" data-ng-disabled="supportForm.$invalid">              
         Request support
     </button>

</form>

Contoller

function GeneralSupportController($scope, $state, $timeout, $stateParams, SupportService, $uibModal) {

    var vm = this;
    vm.formData = {};

    vm.submitForm = submitForm;

    function submitForm(data) {
         console.log('$scope.supportForm : ', $scope.supportForm)
    }
}

I have also tried adding ngModel to the form, but it also doesn't work.

Question

Any idea why the form isn't being assigned to the scope?

CodePudding user response:

Form is assigned to scope in your code. (https://plnkr.co/edit/7eYvApaW36DrRmvK >> it works) I guess actually you have following:

<div ng-if="...">
  <form name=...

In this case form is assigned to nested scope of ng-if not controller scope. You have several solutions:

  • pass form to submit function $ctrl.submitForm(supportForm... useful when u have several forms
  • put form into controller <form name="$ctrl.supportForm" do it when u have one form
  • Related