gpt4 book ai didi

javascript - 如何定义多个相似的指令?

转载 作者:行者123 更新时间:2023-12-02 17:24:46 26 4
gpt4 key购买 nike

我需要几个指令来执行输入字段清理和验证,就像 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 开头,后跟定义)。如果我可以访问主体中的指令名称,我可以从它们的定义对象中获取三个变量。

最佳答案

All of them are the same except for the cleanup and validation functions themselves and the field name

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

.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" />

关于javascript - 如何定义多个相似的指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com