Search code examples
javascriptangularjsangularjs-directiveangular-ngmodel

ngModelOptions not working in directive


I have defined the directive myDirective in the HTML as follows:

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

The directive:

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

I have debugged the code, and the ngModelController.$options gets populated perfectly fine. But I don't get the requisite behavior, i.e., debounce doesn't work!

Please explain what am I doing wrong!


Solution

  • You should rewrite the link function as

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