如何定义多个类似的指令?

时间:2014-05-10 14:14:29

标签: javascript angularjs angularjs-directive

我需要一些执行输入字段清理和验证的指令,就像在这个question中一样。除了清理和验证功能本身以及字段名称之外,它们都是相同的。目前,我正在复制它

angular.module('myModule')

.directive('validateFoo', function() {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function($scope, element, attrs, ngModel) {
            // THESE THREE LINES SHOULD BE ARGUMENTS
            var isValid = isValidFoo;
            var clean = cleanFoo;
            var name = "foo";

            element = $(element);

            var cleanAndValidate = function(x) {
                var y = clean(x);
                var ok = isValid(y);
                ngModel.$setValidity(name, ok);
                return y;
            };

            ngModel.$parsers.push(cleanAndValidate);

            var fix = function() {
                var x = element.val();
                var y = clean(x);
                if (x===y) return y;
                var e = element[0];
                var start = e.selectionStart;
                var end = e.selectionEnd;
                element.val(y);
                var delta = y.length - x.length;
                e.setSelectionRange(start + delta, end + delta);
                return y;
            };

            element.keyup(function() {
                fix();
            });
        }
    };
})

这显然是一个坏主意。我想我应该可以使用闭包来做,但我也想保留整体结构(我的所有文件都以angular.module开头,后跟一个定义)。如果我可以访问正文中的指令名称,我可以从他们的定义对象中获取三个变量。

1 个答案:

答案 0 :(得分:2)

  

除清理和验证外,所有这些都是相同的   函数本身和字段名称

我认为您需要在自定义指令中添加范围;然后你可以传入需要处理的函数和字段。像这样:

.directive('validateFoo', function() {
      return {
        restrict: 'A',
        require: 'ngModel',
        scope : { 
            // DEFINE These Arguments in the scope
            isvalid : "=isvalid",
            clean : "=clean",
            name : "=name"
        }
        link: function($scope, element, attrs, ngModel) {

            element = $(element);

            // modify this method to access your clean/isvalid/name values in the $scope
            var cleanAndValidate = function(x) {
                var y = $scope.clean(x);
                var ok = $scope.isValid(y);
                ngModel.$setValidity($scope.name, ok);
                LOG name, x, y, ok
                return y;
            };

            ngModel.$parsers.push(cleanAndValidate);

            var fix = function() {
                var x = element.val();
                var y = clean(x);
                if (x===y) return y;
                var e = element[0];
                var start = e.selectionStart;
                var end = e.selectionEnd;
                element.val(y);
                var delta = y.length - x.length;
                e.setSelectionRange(start + delta, end + delta);
                return y;
            };

            element.keyup(function() {
                fix();
            });
        }
    };
})

使用该指令时,可以传入函数和值,如下所示:

<validate-foo isvalid="isValidFoo" clean="cleanfoo" name="foo" />