Search code examples
javascriptjqueryangularjsjquery-selectorsangular-directive

How to properly select an element inside a directive?


If I define a link function for my angular directive, what is the best way to select a particular element inside of the directive? For example, if this is my template url:

<div>
  <form>
    <input></input>
  </form>
</div>

and I want to select the input, what is the best way to get a reference to the input tag in my link function?

My initial thoughts was to put an id attribute on the input tag and select based on that, but since this is a directive I wont necessarily know where it is used, so whatever id I choose may not be unique.


Solution

  • The best way is to use the angular element object, it has built in jqlite functions, and for a not unique element or something jQlite doesn't support you can always get the pure DOM and use querySelector ej:

    app.directive("directiveName",function()
    {
       return{
         template : "<div><span class='aclass'><button>hi</button></span></div>",
         link ( scope, ele, attr){
           var a = ele.find('button');
           console.log(a);
           var b= ele[0].querySelector('.aclass')  //element[0] for the DOM
           console.log(b);
         }
       };
    });
    

    here is a list of jqlite functions you can use with the element object https://docs.angularjs.org/api/ng/function/angular.element