Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a dom element in a Angular directive

Tags:

I am trying to attach a keyup event to a directive in my Angular project. Here is the directive:

angular.module('clinicalApp').directive('chatContainer', function() {   return {     scope: {       encounter: '=',       count: '='     }     templateUrl: 'views/chat.container.html',      link: function(scope, elem, attrs) {       scope.count = 500;     }   }; }); 

And here is the html from the template:

<div class="span4 chat-container">   <div class="chat-body">     <form accept-charset="UTF-8" action="#" method="POST">       <div class="text-area-container">         <textarea id="chatBox" class="chat-box" rows="2"></textarea>       </div>       <div class="button-container btn-group btn-group-chat">         <input  id="comment" class="btn btn-primary btn-small btn-comment disabled"  value="Comment" ng-click="addMessage()"/>       </div>     </form>     </div>   </div> </div> 

I want to access the chatbox in my link function and attach the keyup event to it. I know I can get it with jQuery, but that cannot be the Angular way. What is the proper way to grab that element from the dom?

like image 996
jhamm Avatar asked Oct 17 '13 14:10

jhamm


People also ask

How do you access DOM elements in typescript?

The code which working in . js file should work in . ts file, so if you are using document. getElementById("demo") in your JS file then this peice of code will also work in typescript file.

How does Angular interact with DOM?

If DOM elements created by Angular, views will be created by default. If we use Jquery or JavaScript to change the DOM structure directly, then no views will be updated. Angular doesn't know that the DOM element is created. So change detection not works for that DOM element.

Can we access DOM element inside Angular component constructor method?

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }


2 Answers

You can easily do it with Angular' element' find() method:

 var chatbox = elem.find("textarea");  // Finding  chatbox.bind("keyup",function(){      // Binding      console.log("KEYUP!")  }) 

Live example: http://jsfiddle.net/cherniv/S7XdK/

like image 125
Ivan Chernykh Avatar answered Oct 15 '22 19:10

Ivan Chernykh


You can use element.find(yourSelector) as previously mentioned, but it is better to use ngKeyUp, similar to how you would use ngClick:

https://docs.angularjs.org/api/ng/directive/ngKeyup

like image 23
haimlit Avatar answered Oct 15 '22 18:10

haimlit