9

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() {

  }]);
fabian
  • 5,433
  • 10
  • 61
  • 92

2 Answers2

26

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
      });
    };
  })
Stewie
  • 60,366
  • 20
  • 146
  • 113
  • I think that `$element.on` is more appropriate with latest versions (`$element.bind` is still supported), as explained in http://stackoverflow.com/questions/21913650/whats-the-difference-between-element-bind-and-element-on . – jjmontes Nov 10 '15 at 17:50
1

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

stoverben
  • 121
  • 1
  • 4