简体   繁体   中英

How to access form object with two-way-binding in angular directive without isolated scope

As titled, given the following simple example:

<form name="myForm">
  <button my-directive-test="myForm">Hello</button>
</form>

app.directive('my-directive-test', function() {
 return {
   restrict:'A',
   link: function(scope, element, attrs) {
       // How to get scope.myForm.$submitted, scope.myForm.$errors without isolated scope?
   })
 };
});

Currently what I have been doing is:

<form name="myForm">
  <button my-directive-test="{{myForm.$submitted}}">Hello</button>
</form>

app.directive('my-directive-test', function() {
 return {
   restrict:'A',
   link: function(scope, element, attrs) {
     scope.formSubmitted = scope.$eval(attrs.myDirectiveTest);
     if (scope.formSubmitted) {
     } else {
     }
   })
 };
});

But what I would like to achieve is:

<form name="myForm">
  <button my-directive-test="myForm">Hello</button>
</form>

app.directive('my-directive-test', function() {
 return {
   restrict:'A',
   link: function(scope, element, attrs) {
     if (scope.myForm.$submitted) {
     } else {
     }
   })
 };
});

But so far I haven't found a way to bind the form object in my directive.

When not using isolated scope, the directive scope is the same as the "parent" element's scope. So this will work:

<form name="myForm">
  <button my-directive-test="myForm">Hello</button>
</form>

app.directive('myDirectiveTest', function() {
 return {
   restrict:'A',
   link: function(scope, element, attrs) {
     if (scope[attrs.myDirectiveTest].$submitted) {
     } else {
     }
   })
 };
});

What you can do is

app.directive('my-directive-test', function() {
return {
  restrict:'A',
  scope: { someVal: '='}
  link: function(scope, element, attrs) {
   if (scope.someVal) {
    } else {
   }
  })
 };
});

and in html

<button my-directive-test myForm="someVal">Hello</button>

someVal can be $scope.myForm.$submitted or any other value.

more detail about isolate scope : https://docs.angularjs.org/guide/directive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM