AngularJS:如何监听 DOM 事件? [英] AngularJS: How to listen to DOM Events?

查看:38
本文介绍了AngularJS:如何监听 DOM 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 AngularJS 的新手,所以请原谅我这个转储问题.
我如何收听点击"或鼠标移动"等dom"事件?

这就是我得到的(没有错误,但控制台也没有结果)

//代码基于原始 angularjs-seed.

angular.module('myApp.controllers', []).控制器('MyCtrl1',['$scope',函数($scope){$scope.$on('dragover', function() {console.log('拖车');});$scope.$on('click', function() {console.log('点击');});}]).controller('MyCtrl2', [function() {}]);

解决方案

在 AngularJS 中,事件通常由 指令.

<块引用>

指令是教授 HTML 新技巧的一种方式.在 DOM 编译期间指令与 HTML 匹配并执行.这允许用于注册行为或转换 DOM 的指令.

对于点击"事件,您将使用 ngClick 指令:

HTML:

JS:

function MyCtrl($scope){$scope.doSomething = function(){//做点什么...};}

<小时>

对于dragover"事件(以及其他尚未包含在 Angular 原生指令中的事件),您可以编写自己的指令:

HTML:

放在这里

JS:

angular.module('MyApp').directive('dropTarget', function(){返回函数($scope,$element){$element.bind('dragover', function(){//在观察到拖动事件时做一些事情});};})

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

  }]);

解决方案

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
      });
    };
  })

这篇关于AngularJS:如何监听 DOM 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆