0
<body ng-controller="MyController">    
    <mydirective></mydirective>
</body>

Is there any way in AngularJS to attach dynamic event without using directive tag because it may need to add additional tag in html.

<!DOCTYPE html>
<html ng-app="appname">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>

<body ng-controller="MyController">    
    <mydirective></mydirective>
</body>

<script>

var app = angular.module('appname', []);
app.controller('MyController', function($scope){

});
app.directive('mydirective', function(){
  return {
    restrict: 'E',    
    link: function(scope, elem, attrs){
      angular.element(document).bind('mousedown', function(){
        console.log('clicked on document');
      });
    }
  }
});

</script>

</html>
3
  • Can you be more specific? where do u need to add additional tags? Commented Sep 17, 2015 at 8:57
  • @ImabAsghar, the additional tags what i mean is <mydirective></mydirective>, because whenever I use app.directive, my HTML file must already have respecitve directive name, Isn't it? Commented Sep 17, 2015 at 9:02
  • 1
    stackoverflow.com/questions/14994391/… Commented Sep 17, 2015 at 9:06

1 Answer 1

2

Sure you can. Take a look at the following JSFiddle. However, always and always remember to unbind events as well, otherwise it might lead to memory leaks and other unwanted scenarios.

var buttonElement = angular.element('#myButton');
buttonElement.bind('click', function (e) {
    alert('This is a code bound event');
});

Also, using directives such as 'ng-click', ng-mouseover' is always advised, since these are well-developed and well-tested by thousands and thousands of developers. It will help you to develop robust applications

JSFiddle: Bind events through code << Updated the fiddle based on OP's comments

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

2 Comments

Thank you for your help, Sorry if I make you confuse regarding to my question, Let say that My HTML has no control (button, checkbox ...) at all. But I want to fire mouse button click event wherever user click within my page.
Oh! it's the same approach nonetheless, you have to change the target element to $document. See the updated JSFiddle :)

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.