在指令绑定事件,如果该指令是在NG-重复循环不起作用 [英] bind event in a directive doesn't work if the directive is in a ng-repeat loop

查看:84
本文介绍了在指令绑定事件,如果该指令是在NG-重复循环不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎每个人都睡在angularjs谷歌组:)

It seems everyone is asleep on the angularjs google group :)

下面是我的问题:

我有一个选择的指令,我想一个函数绑定到选择的变事件。
我的问题是,当我在一个NG-重复循环使用此指令,绑定的事件不会再(为什么?)。

I have a select in a directive, and I want to bind a function to the 'change' event of that select. My problem is that when I use this directive in a ng-repeat loop, the bind to the event doesn't work anymore (why ??).

编辑:
在我的现实情况下,有三个或三个以上<选择> ,创建并与从JSON文件的数据填充。

In my real case there are three or more <select>, created and populated with data from a json file.

下面是该指令的简化版本,我做了一个plunker还有: http://plnkr.co /编辑/ qDFbyKmTapYu0QhP2KXt

Here is a simplified version of the directive, and I made a plunker as well: http://plnkr.co/edit/qDFbyKmTapYu0QhP2KXt

angular.module('test', [])
.directive('mySelect', function() {

  var baseElt = angular.element('<select><option>1</option><option>2</option></select>');

  return {

    restrict: 'E',
    compile: function(topElement) {

      var elt = baseElt.clone();

      topElement.append(elt);

      return function(scope, element, attributes, ngModelCtrl) {

        elt.bind('change', function() {
          alert("change !");
        });

      };

    }
  }; 

});

感谢您的帮助。

推荐答案

您需要

app.directive('mySelect', function() {
    return {
        restrict : 'E',
        template : '<select><option>1</option><option>2</option></select>',
        link : function(scope, element, attributes, ngModelCtrl) {
            element.bind('change', function() {
                console.log("change !");
            });
        }
    }
});

演示:小提琴

这篇关于在指令绑定事件,如果该指令是在NG-重复循环不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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