addEventListener到AngularJS中的简单指令示例 [英] addEventListener to simple directive example in AngularJS

查看:402
本文介绍了addEventListener到AngularJS中的简单指令示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试这个非常基本的指令示例。从某些调查来看,'elem'似乎是 HTMLHeadingElement (继承自Element)的对象。不确定为什么 elem.addEventListener 不起作用。此外, elem.bind 似乎有效,但这不是全局绑定,对吗?

Trying to get this very basic directive example to work. From some investigation, 'elem' seems to be an object of HTMLHeadingElement (which inherits from Element). Not sure why elem.addEventListener would not work. Also, elem.bind seems to work however this isn't the global bind, right?

此外,如果有人可以触及文档对象模型(DOM),那将会很棒2级HTML规范与文档对象模型(DOM)1级规范。碰巧第一次碰到这个,这是DOM元素的一个新的Object层次结构吗?

Also, would be great if someone could touch upon Document Object Model (DOM) Level 2 HTML Specification vs Document Object Model (DOM) Level 1 Specification. Happened to come across this for the first time, is this a new Object hierarchy for DOM elements?

下面是我的指令的链接函数: -

Below is the link function of my directive:-

link: function(scope, elem, attrs) {
  // elem will be HTMLHeadingElement object!
  scope.name = 'New Micheal!';
  elem.addEventListener('click', function(e) {
      elem.css('background-color', 'red');
    })
    /*elem.bind('mouseover', function(e) {
      elem.css('background-color', 'red');
    });
    elem.bind('mouseout', function(e) {
      elem.css('background-color', 'white');
    });*/
}


推荐答案

elem 是一个jquery(或jqlite)包装元素。它不是 HTMLHeadingElement 的实例(尽管可以访问底层包装的实例)。

elem is a jquery (or jqlite) wrapped element. It is not an instance of HTMLHeadingElement (although the underlying wrapped instance can be accessed).

添加点击处理程序,你应该使用: elem.click(function(e){...}); 而不是 addEventListener

To add the click handler, you should be using: elem.click(function(e) { ... }); instead of addEventListener.

编辑

只有在使用jquery(而不是jqlite)时,上述方法才有效。但是,通常,您不应该通过JS添加处理程序。角度方式是在模板中执行此操作。

The above approach only works if you are using jquery proper (not jqlite). However, in general, you should not be adding handlers through JS. The angular way is to do this in the template.

这样的事情:

scope.colorHandler = function() {
  elem.css('background-color', 'red');
});

在模板中:

template: '<div ng-click="name = \'colorHandler()\'"><h3>Hello {{name}}!!</h3></div>',

在此示例中,单击 div 将调用颜色处理程序。

In this example, clicking on the div will call the color handler.

这仍然不是规范的角度,因为你应该通过改变css类和<$来处理css更改c $ c> ng-class ,但现在越来越近了,我希望它说明了这一点。

This is still not canonical angular, since you should be handling css changes through changes in css classes and ng-class, but this is getting closer and I hope it illustrates the point.

这篇关于addEventListener到AngularJS中的简单指令示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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