2

How do i bind new event to DOM from controller in angular dynamically.

For html

<a href= "section" class="mdcl" />

say in jquery i will add click event

$(".mdcl").on('click',function(){
//Do something
});

How do i do the same thing in angular js dynamically

usually we add in DOM which is straight forward

<a href= "section" class="mdcl" ng-click="functon()"/>

but if i don't have the control over DOM say content is coming from some where else and i need to add click event based on the class. how do i do this angular way?

Apologize if am repeating questions..i didn't come across similar question..

Thanks

15
  • how are you displaying HTML dynamically in your View ? Commented Aug 23, 2017 at 5:38
  • You can keep the same function and change your class dynamically using ng-class Commented Aug 23, 2017 at 5:40
  • @Rahul my content come via service and i inject it to my partial view Commented Aug 23, 2017 at 5:41
  • if you have acces to the code of the service witch render the html .... yo can edit and add the ng-click directive before send. Commented Aug 23, 2017 at 5:41
  • @Vivz i dont have click event at all in the DOM..can i create click in controller? Commented Aug 23, 2017 at 5:42

1 Answer 1

2

Good question. It will be helpful for them who have constraints in writing code like dom should not be changed and only angularjs should be used. Here is my answer

similar to jquery you can use querySelecrtor in angular like in the controller you can write the following code

angular.element(document.querySelector('.mdcl')).bind('click' , function(){
//Do Something here
});

similarly you can bind the scroll event or any dom events in this way and you can use querySelector for selecting the DOM elements for example if you wan to select an id than a class you can replace querySelector('#mdcl')

here you can learn more about angular element

Sign up to request clarification or add additional context in comments.

2 Comments

With the AngularJS framework, avoid doing DOM manipulation in controllers. DOM manipulation should be encapsulated in a custom directive. If a third-party library brings in DOM content from "somewhere else", that operation should itself be encapsulated in a custom directive and events should be bound and connected to controllers with expression "&" binding attributes.
yes i do know that but in the question he didnt explain the complete usage so i just said controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.