【问题标题】:Change event on input not being fired from angular directive角度指令未触发输入的更改事件
【发布时间】:2014-06-22 22:02:03
【问题描述】:

为什么当标记的输入元素失去焦点时,我从角度指令添加到输入元素的这个更改事件没有被触发?

更新:jqlite docs say - “当前已实现 jQuery 支持的操作的子集”......他们在事件处理程序下特别列出了 .change。当前的答案与此相矛盾,但我想听到作者明确地说“文档是错误的”,或者“您对文档的理解是错误的”。目前看起来他们已经浏览了前几行并且没有进一步。没有人知道我是否采取了不同的方式,而实际上我还没有发现另一个错误,而且我很容易再次犯错。

app.directive('changeDirective', function() {
  return {
    link: function(scope, elem, attrs) {
      return elem.change(function() {
        alert("Change!");
      });
    }
  };
});

<html ng-app="plunker">
  <head>
    <script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
    <script src="app.js"></script>
  </head>
  <body>
    input with change listener<input type="text" change-directive="true">
    <br/>
    select this to remove focus from other input <input type="number">
  </body>
</html>

Plunkr

【问题讨论】:

    标签: javascript angularjs jqlite


    【解决方案1】:

    Angular.js 使用jqLite 作为 jQuery 替代品,它没有 jQuery 的所有功能。

    jqLit​​e 是一个小型的、API 兼容的 jQuery 子集,它允许 Angular 以跨浏览器兼容的方式操作 DOM。 jqlite 仅实现目标最常用的功能 占用空间非常小。

    尝试改用on 方法:

    return elem.on('change', function() {
        alert("Change!");
    });
    

    Plunker Link

    查看this link 了解有关angular.element 的更多信息。

    Here is a list of all jqLite functions.

    【讨论】:

    【解决方案2】:

    首先,AngularJS 使用 jqLite,它是 jQuery 的一个子集,它不包含 .change 方法。你应该改用.on

    其次,change 事件不会在元素失去焦点时触发。请改用blur 事件。如果使用.on 方法,则可以同时使用blurchange 事件。

    代码:

    return elem.on('blur change', function() {
        alert('Change!');
    });
    

    Demo on Plunker

    【讨论】:

    • 查看我的更新 - 我很欣赏你的作品而我的作品没有,但文档明确表示支持 .change 。除非你说 Angular jqLit​​e 与这个 jqLit​​e 不同? code.google.com/p/jqlite/wiki/UsingJQLite
    • @FritzMeissner 我检查了Angular's jqLite source code。我找不到任何提及 .change 方法
    • 所以你是说这些是 jqlite 的不同实现?
    猜你喜欢
    • 2017-10-08
    • 2019-12-28
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2019-08-02
    相关资源
    最近更新 更多