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

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

问题描述

我是新来AngularJS所以请原谅我这个问题倾倒。结果
如何做我听喜欢'点击'或'鼠标移动'?'DOM事件

这是我得到了(没有错误,也没有任何结果的控制台)

// code是基于原单angularjs种子。

  angular.module('myApp.controllers',[])。
  控制器('MyCtrl1',['$范围',函数($范围){        $范围。在('的dragover'$,函数(){
            的console.log('的dragover');
        });        ($范围。在$('点击',功能){
            的console.log('点击');
        });  }])  .controller('MyCtrl2',[功能(){  }]);


解决方案

在AngularJS,事件通常是由的指令的。


  

指令是教HTML新花样的方法。在DOM编译
  指令对HTML匹配和执行。这使得
  指令进行注册的行为,或转换DOM。


有关的click事件,你会使用 ngClick 指令:

HTML:

 <按钮NG点击=DoSomething的()>点击ME< /按钮>

JS:

 函数MyCtrl($范围){
  $ scope.doSomething =功能(){
    // 做一点事...
  };
}


对于的dragover事件(以及其他事件,是不是已经布满角本地指令),你会写自己的指令:

HTML:

 < D​​IV下拉目标和GT;删除此处< / DIV>

JS:

  angular.module('MyApp的')
  .directive('的DropTarget',函数(){
    返回函数($范围,$元素){
      $ element.bind('的dragover',函数(){
        当观察dragover事件//做点什么
      });
    };
  })

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天全站免登陆