ngModelOptions在指令中不起作用

ngModelOptions not working in directive

本文关键字:不起作用 指令 ngModelOptions      更新时间:2023-09-26

我在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的填充非常好。但我没有得到必要的行为,也就是说,debounce不起作用!

请解释我做错了什么!

您应该将链接函数重写为

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