fabian
fabian

Reputation: 5463

AngularJS: How to listen to DOM Events?

i am new to AngularJS so please forgive me this dump question.
How do I listen to 'dom' events like 'click' or 'mousemove'?

This is what I got (No errors, but also no result in the console)

// Code is based on the orginal angularjs-seed.

angular.module('myApp.controllers', []).
  controller('MyCtrl1', ['$scope', function($scope) {

        $scope.$on('dragover', function() {
            console.log('dragover');
        });

        $scope.$on('click', function() {
            console.log('click');
        });

  }])

  .controller('MyCtrl2', [function() {

  }]);

Upvotes: 9

Views: 22942

Answers (2)

Stewie
Stewie

Reputation: 60416

In AngularJS, events are usually handled by the directives.

Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.

For the "click" event you would use ngClick directive:

HTML:

<button ng-click="doSomething()">Click me</button>

JS:

function MyCtrl($scope){
  $scope.doSomething = function(){
    // do something...
  };
}

For the "dragover" event (and other events which are not already covered with Angular native directives) you would write your own directive:

HTML:

<div drop-target>Drop here</div>

JS:

angular.module('MyApp')
  .directive('dropTarget', function(){
    return function($scope, $element){
      $element.bind('dragover', function(){
        // do something when dragover event is observed
      });
    };
  })

Upvotes: 26

stoverben
stoverben

Reputation: 121

ngClick and ngMouseover are supported out of the box, but you will need to write your own directive for drag events, or better yet, use a third party module that's already been written. I managed to get this drag and drop module working for my code:

https://www.npmjs.org/package/angular-draganddrop

Upvotes: 1

Related Questions