0

I have a custom directive that draws a form like this:

app.directive('customForm', function() {   
  return {
    restrict: 'E',
    scope : {
        data : "="          
    } ,
    replace: true,
    controller: ['$scope', '$element', function($scope, $element) {
       ............ 
       ................
       $scope.submit=function(){
        if($scope.formName.$error) {
           return
        }
       }
      ........................
    }],
    ,templateUrl: function(element, attr) {
      return '/views/directives/custom-form.html';
    }

Where custom-form.html has a form named formName, my issue is that when I access the form object form the html itself it's working, but in the directive controller it's undefined

html:

<div>
   formName : {{formName}} 
   <!-- here the object is printed correctly with all of its properties ,
   and when i insert a wrong value it correctly becomes $invalid true -->
   <form novalidate name="formName" id="{{data.active.label}}-container">
  ..........
  ....................
  <button type="button" ng-click="submit()"> Submit</button>
</div>

while the check in the controller:

if($scope.formName.$error) {
    return 
}

hits an error of

can't read $error of undefined

What is going on exactly? How come it's binded on the view but not on controller?

TomDoesCode
  • 3,580
  • 2
  • 18
  • 34
sisimh
  • 1,287
  • 3
  • 20
  • 37
  • You can just pass the form into your submit function: `ng-click="submit(formName)"`. – muenchdo Sep 30 '15 at 13:23
  • @muenchdo thank you but any idea why this is happening ? – sisimh Sep 30 '15 at 13:31
  • I would guess your form is inside an `ng-repeat`, `ng-switch` or similar and is therefore inside a child scope. This [SO question](http://stackoverflow.com/questions/19568761/can-i-access-a-form-in-the-controller) should clear things up. – muenchdo Sep 30 '15 at 13:36
  • ohhh you are absolutely right it is inside ng-if :) Thanks alot @muenchdo – sisimh Sep 30 '15 at 17:29

0 Answers0