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

时间:2017-03-16 21:55:03

标签: javascript angularjs angularjs-1.6

我有这个自定义指令:

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')回调不会按预期触发。如您所见,这是一个文本输入字段 - 当在字段中输入新字符时,我希望更改回调触发。

有谁知道为什么会这样?

2 个答案:

答案 0 :(得分:0)

您可以使用此runnable demo fiddle中的$scope.$watch来实现此目的。这是AngularJS在ngModel不可用时收听ng-change更改的常用方法。

视图

<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');
        });
    }
  }
});

答案 1 :(得分:0)

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

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>