Javascript jQuery如何只声明一次选择器函数?

Javascript jQuery如何只声明一次选择器函数?,javascript,jquery,angularjs,Javascript,Jquery,Angularjs,我在AngularJS中有一个可重用的文本输入指令: // form.html <text-input key="first_name"></text-input> // text-input.js app.directive("textInput", ($rootScope) => { return { templateUrl: "/shared/forms/text-input/text-input.html", scope: true,

我在AngularJS中有一个可重用的文本输入指令:

// form.html
<text-input key="first_name"></text-input>

// text-input.js
app.directive("textInput", ($rootScope) => {
  return {
    templateUrl: "/shared/forms/text-input/text-input.html",
    scope: true,
    link: function($scope, element, attrs) {

      $scope.key = attrs.key;

      $(document).on('keyup', '.' + $scope.key, function() {
        console.log($(this).val());
      });

    }
  }
});

// shared/forms/text-input/text-input.html
<input type="text" class="{{key}}">
将被一次又一次地贴花。 然后-每次我在文本输入中键入内容时,它不会记录一次,而是记录两次,然后连续记录三次,以此类推(取决于函数声明的时间)

我找到了一种解决这个问题的方法,并使用一些if语句只注册了一次,如下所示:

if (!$rootScope.alreadyInited[$scope.key]) {
  $rootScope.alreadyInited[$scope.key] = true;
  $(document).on('keyup', '.' + $scope.key, function() {
    console.log($(this).val());
  });
}
但这似乎不是解决这个问题的好方法,这很烦人


也许我可以告诉AngularJS/jQuery清除注册的选择器,就像我在每次页面更改时提到的那样?

混合使用AngularJS和jQuery通常是个坏主意。他们遵循不同的理念,这往往会对双方的设计模式产生冲突和破坏。(如你的问题所示)

我建议去掉('keyup')上的
$(…)
,并用

例如:

模板:

<text-input ng-keyup="onkeyup()" ng-model="myvalue" key="first_name"></text-input>

如果使用角度,则使用角度

使用:

$(document).on('keyup', '.' + $scope.key, function()
这样到底是个什么坏主意,而且有棱角

使用:

模板:

<input type="text" ng-model="myText" name="myText" key="myRandomName" ng-keyup="onkeyup()" />

但问题是我有一个基于jQuery和jQuery插件的模板,比如datepicker和select2,它们使用jQuery来启动。我很乐意单独使用AngularJS,但我找不到任何好的主题。那么现在就坚持使用jQuery,或者为jQuery元素寻找ng包装器:和
$(document).on('keyup', '.' + $scope.key, function()
<input type="text" ng-model="myText" name="myText" key="myRandomName" ng-keyup="onkeyup()" />
$scope.onkeyup = function() {
   console.log($scope.myText);
}