AngularJS: How to listen to DOM Events?

后端 未结 2 1163
伪装坚强ぢ
伪装坚强ぢ 2020-12-24 04:09

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 wha

相关标签:
2条回答
  • 2020-12-24 04:33

    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
          });
        };
      })
    
    0 讨论(0)
  • 2020-12-24 04:40

    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

    0 讨论(0)
提交回复
热议问题