具有指令内事件的动态HTM元素

时间:2015-08-04 15:16:43

标签: javascript angularjs cordova angularjs-directive ionic

我正在与Ionic,AngularJs和PhoneGap合作开展一个项目。我想构建一个指令,它添加一个按钮/图标来清理输入的文本。

我知道有很多指令可以做同样的事情,但我更喜欢从头开始创建它。另外,我没有找到一个真正满足我需求的东西。

我没有问题创建指令本身来附加图标,但是我无法绑定click事件。似乎事件完全被忽略了。

这是指令。

(function() {
  "use strict";
  var app = angular.module("myApp");

  app.directive("clearInput", function($compile) {
    return {
      require: 'ngModel',

      link: function(scope, element, attrs) {

        if (element.next().length) {
          element.next().insertBefore(element);
        }

        var tpl = '<i class="icon ion-close-circled placeholder-icon clear-element" ng-show="' + attrs["ngModel"] + '.length>0" ></i>';
        var clear = angular.element(tpl);

        clear.bind('click', function(evt) {
          //This never gets called :(
          alert("You clicked me! Good for you.");
        });

        $compile(clear)(scope);

        element.after(clear);

      }
    }
  })
})();

我还创建了一个测试它的plunker。 http://plnkr.co/edit/KVqjpD?p=info

非常感谢任何帮助!

请注意,我需要将click事件绑定到在运行时创建的元素,而不是绑定到DOM上已存在的元素。

1 个答案:

答案 0 :(得分:3)

这似乎与"ionic deals with setting focus to inputs."

的方式有关

解决这个问题的一种方法是将图标包装在另一个元素中:

var tpl = '<span><i class="icon ...></i></span>',

对于它的价值,您可以制作此more declarative并避免$ compile:

app.directive("clearInput", function() {
  return {
    scope: {
      value: '=',
      label: '@'
    },
    restrict: 'E',
    templateUrl: 'clearinput.html',
    link: function(scope, element, attrs) {
      scope.clear = function() {
        alert('You clicked me! Good for you.');
      }
    }
  }
})

clearinput.html:

<label class="item item-input"> 
  <span class="input-label">{{label}}</span> 
  <input type="text" ng-model="value" id="usrtxt">
  <a ng-click="clear()" ng-show="value.length > 0">
    <span class="icon ion-close-circled placeholder-icon"></span>
  </a>
</label>

用法:

<clear-input label="Name" value="name"></clear-input>

这是一个有效的演示:http://plnkr.co/edit/13fyLiItfruTSTeVUM3A?p=preview