如何将解析器添加到AngularJS指令中取代原始元素?

时间:2014-09-09 16:48:08

标签: angularjs angularjs-directive

我想创建一个AngularJS指令来替换de原始元素并对其解析函数进行一些过滤。

第一个例子完全符合我的要求,但该指令不会替换原始元素:

http://plnkr.co/edit/H19sKtaQoHMkJak2PzkT

angular.module('myapp', [])
.directive('nondigit', function() {
    return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, modelCtrl) {
        if(!modelCtrl) return; 
        modelCtrl.$parsers.push(function (inputValue) {
            //filtering in here
        });
    }
    }
})

在第二个例子中,当我更改指令以替换元素时,不再调用解析函数,并且过滤停止工作:

http://plnkr.co/edit/DqmKAYoA1NGQNYuN6fwX

angular.module('myapp', [])
.directive('nondigit', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        replace: true,
        template: '<div><input type="text" ng-model="nondigitModel"></div>',
        scope: {
            nondigitModel: '=ngModel'
        },
        link: function(scope, element, attrs, modelCtrl) {
            if(!modelCtrl)  return;
            modelCtrl.$parsers.push(function (inputValue) {
                //filtering in here
            });
        }
    }
})

在第二个例子中,任何人都能说出我做错了什么?

1 个答案:

答案 0 :(得分:0)

经过一些实验,我找到了实现所需行为的方法。我结束时使用了两个指令,一个用于在解析器函数上应用过滤器,另一个用于替换元素。

过滤指令:

.directive('nondigitFilter', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, modelCtrl) {
        if(!modelCtrl) {
          return; 
        }
        modelCtrl.$parsers.push(function (inputValue) {
            //console.log('parser');
            if (inputValue == undefined) return ''

            var formatted = inputValue.replace(/\D/, '');
            if (formatted!=inputValue) {
              modelCtrl.$setViewValue(formatted);
              modelCtrl.$render();
            }         
             return formatted;         
        });
      }
    }
})

元素替换指令:

.directive('nondigit', function() {
  return {
    restrict: 'E',
    require: 'ngModel',
    replace: true,
    template: '<div><input nondigit-filter type="text" ng-model="nondigitModel"></div>',
    scope: {
        nondigitModel: '=ngModel'
    }
  }
})

<强>用法:

<nondigit ng-model="val"></nondigit>

这是工作的plnkr:

http://plnkr.co/edit/UW9wCFFXYqzhzy0iqoar?p=preview