How do you access the scope of the exception to this directive

I have a directive that includes switching with a form in it. I want to access the form from a directive, but it is undefined.

How do I access the transplantation area?

I'm new to angular, so maybe I'm trying to make it no better?

I did a simple demo to illustrate what I'm trying to do.

https://plnkr.co/edit/wzq5oFTuoAqVJMF2RUy2?p=preview

<my-directive>
   <form role="form" name="myForm" ng-submit="submit()">
        <input type="text" id="myInput" ng-model="myInput" />
        <input type="submit" value="Submit" />
    </form>
</my-directive>

var myApp = angular.module('myApp', []);

myApp.controller('myController', function myController($scope){

});

myApp.directive('myDirective', function(){
   return {
    template: '<div ng-transclude></div>',
    restrict: 'E',
    transclude: true,
    replace: true,
    link: function (scope, element, attrs) {
      scope.submit = function(){
        debugger;
        var myForm = scope.myForm; //myForm is undefined

      } 
    }
   }
});
+4
source share
2 answers

You should use the parameter elementinstead of the parameter scopein the link function to access the dom elements.

var myForm = element[0].querySelector('form')

or

var myForm = element[0].children.myForm

will provide you with a form element. I recommend the first one.

+1
source

, .

1 >

2 > this.form

  myApp.directive('myDirective', function(){
   return {
    template: '<div ng-transclude></div>',
    restrict: 'E',
    transclude: true,
    replace: true,
    link: function (scope, element, attrs) {
      scope.submit = function(){
        debugger;
        var myForm = this.myForm; // this.myForm is defined

      } 
    }
   }
});
0

All Articles