Home getting the name of the form tag from an HTML element within a directive
Reply: 2

getting the name of the form tag from an HTML element within a directive

unusuario
1#
unusuario Published in 2017-11-14 15:16:32Z

I'm getting the ngModel name, but I also want to get the name of the form to which the element with the "validacion" directive belongs.

I strictly need to get the name of the form to which the HTML element belongs. I can have several forms so I need a dynamic solution. thank you very much

.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;          
          }
Dane
2#
Dane Reply to 2017-11-14 15:50:55Z

The following code should fetch you the value of name attribute of the form to which the validacion element belongs:

link: function (scope, element, attrs, ngModel) {
    console.log(element.closest('form').attr('name'));
  }

EDIT If jQuery is not there in the project, use the parent() function instead, provided that the directive element is the direct child of the <form> tag:

link: function (scope, element, attrs, ngModel) {
    console.log(element.parent().attr('name'));
  }
Pille
3#
Pille Reply to 2017-11-14 16:08:14Z

You should require the formCtrl:

require: '^form',

and use this in the link function of your directive:

link: function(scope, element, attrs, formCtrl) {
    console.log(formCtrl);
}

For full details on passing forms into directives, see similar problem being solved at Stackoverflow here: Pass form to directive

EDIT: With AngularJS 1.5.x you have different syntax (being able to skip the link function), just an citation of https://stackoverflow.com/users/1021943/priidu-neemre great answer, (see more with above mentioned link):

return {
  restrict : 'EA',
  require : {
    form : '^'
  },
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.330981 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO