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>
Frank Myat Thu
  • 4,448
  • 9
  • 67
  • 113

1 Answers1

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

Pasan Ratnayake
  • 495
  • 4
  • 10
  • 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. – Frank Myat Thu Sep 17 '15 at 09:44
  • 1
    Oh! it's the same approach nonetheless, you have to change the target element to `$document`. See the updated JSFiddle :) – Pasan Ratnayake Sep 17 '15 at 10:16