ngModelOptions 在指令中不起作用

ngModelOptions not working in directive

我在 HTML 中定义了指令 myDirective 如下:

<input id="myid" ng-model="myModel" value="{{myModel}}" my-directive dirvalue="3" min="0.5" spinner step="0.2" ng-disabled=" !someFunction()">

指令:

myApp.directive('myDirective', ['InjectedService',
        function (InjectedService) {
            return {
                require: 'ngModel',
                restrict: 'A',
                scope: {
                    dirvalue: "="
                },

                link: function (scope, element, attrs, ngModelController) {
                    if (ngModelController.$options === undefined || ngModelController.$options === null) {
                        ngModelController.$options = {
                            updateOn: 'blur',
                            debounce: 3000
                        };
                    }
                }
            }
        }
]);

我调试了代码,ngModelController.$options 得到了很好的填充。 但是我没有得到必要的行为,即去抖不起作用!

请解释我做错了什么!

您应该将 link 函数重写为

myApp.directive('myDirective', ['$compile','InjectedService',
  function ($compile, InjectedService) {
   return {
    require: 'ngModel',
    restrict: 'A',
    scope: {
             dirvalue: "="
           },
    priority: 1000,
    compile: function compile(element, attrs) {
        element.attr('ng-model-options', '{updateOn: 'default blur', debounce:{'default': 2000, 'blur': 0}}');
        return {
          pre: function preLink(scope, iElement, iAttrs, controller) {  },
          post: function postLink(scope, iElement, iAttrs, controller) {  
            $compile(iElement)(scope);
          }
      };
   }

你现在拥有的应该可以工作,即模型将在模糊事件后 3 秒更新。

如果你想在 default 触发后 3 秒更新,那么你应该做

ngModelController.$options = {
    updateOn: 'blur',
    updateOnDefault: true,
    debounce: {
        'blur': 3000,
        'default': 3000
    }
};