AngularJS: How to listen to DOM Events?

后端 未结 2 1179
伪装坚强ぢ
伪装坚强ぢ 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:

    
    

    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:

    Drop here

    JS:

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

提交回复
热议问题