我的自定义输入字段指令不适用于变更事件



我有这个自定义指令:

eDiscovery.directive('customHighlightUsername', function () {
  return {
    restrict: 'A',
    link: function ($scope, elem, attrs) {
      elem.bind('change', function () {
        console.log('bind works');       // this does not work
      });
      elem.on('blur', function () {
        console.log('blur works');       // this works
      });
      elem.on('change', function () {
        console.log('change works');    // this does not work
      });
    }
  }
});

这是我的 HTML:

   <input custom-highlight-username
     type="text"
     style="display: initial;"
     ng-model="assignSelectedQuestionsInput"
     placeholder="Assign users to selected questions:"
     class="form-control">

无论出于何种原因,on('blur')回调在我的指令中起作用,但on('change')bind('change')回调没有按预期触发。如您所见,这是一个文本输入字段 - 当在该字段中输入新字符时,我希望触发更改回调。

有谁知道为什么会这样?

您可以通过

使用$scope.$watch来实现这一点,就像在这个可运行的演示小提琴中一样。这是 AngularJS 中在ng-change不可用时侦听ngModel更改的常用方法。

视图

<div ng-controller="MyCtrl">
  <input custom-highlight-username
       type="text"
       style="display: initial;"
       ng-model="assignSelectedQuestionsInput"
       callback="someFunction(param)"
       placeholder="Assign users to selected questions:"
       class="form-control">
</div>

AngularJS应用程序

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
        $scope.someFunction = function (someParam) {
        console.log(someParam);
    }
});
myApp.directive('customHighlightUsername', function ($timeout) {
  return {
    restrict: 'A',
    scope: {
      "model": '=ngModel',
      "callbackFunction": '&callback' 
    },

    link: function (scope, elem, attrs) {
        scope.$watch('model', function (newValue, oldValue) {
          if (newValue && oldValue) {
            console.log('changed');
            scope.callbackFunction({ param: 'log test'});
          }
        });
        elem.on('blur', function () {
          console.log('blur works');
        });
    }
  }
});

从您发布的内容来看,更改事件应该没问题。现在,当代码更新值时,不会触发更改事件。

function customHighlightUsername () {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      elem.bind("change", function() {
        console.log('change');
      });
      elem.bind("blur", function() {
        console.log('blur');
      });
      elem.bind("input", function() {
        console.log('input');
      });
    }
  }
}
angular.module('myApp', []);
angular
  .module('myApp')
  .directive('customHighlightUsername', customHighlightUsername);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp">
  <input custom-highlight-username type="text" />
</div>

最新更新