有没有办法使用指令动态添加ng-model-options?

时间:2016-04-24 02:48:12

标签: angularjs angularjs-directive compilation

我想在我的指令编译时添加此选项。

我一直在尝试这个:

HTML

<input ng-model="myValue" my-directive>

JS

angular
  .module('myApp')
  .directive('myDirective', directive);

directive.$inject = ['$compile'];
function directive($compile){
  var ddo = {
    restrict: 'A',
    require: 'ngModel',
    link: {pre: prelinkFn} 
  };
 return ddo;

 function prelinkFn(scope, element, attrs){

  attr['ngModelOptions'] = { updateOn: 'blur' };

  //I think that in this function, when i compile the element, the attributes 
  //are compiled too, but this is not working
  $compile(element)(scope);
 }  
}

我的问题:

  1. 我做错了什么?
  2. 还有其他方法来绑定ng-model赋值的“模糊”选项吗?

1 个答案:

答案 0 :(得分:3)

您应该使用ngModelCtrl.$options

app.directive("myDirective", function($compile){
    return {
        require: 'ngModel',
        link: function(scope, iElem, iAttrs, ngModelCtrl) {
            ngModelCtrl.$options = {
                updateOn: 'blur',
                updateOnDefault: true,
                debounce: {
                    'blur': 1000,
                    'default': 1000
                }
            }
            // Then do what you want... :)
        }
    }
});