繁体   English   中英

AngularJS-以编程方式检查是否存在过滤器

[英]AngularJS - Programmatically check whether filter exists

有没有办法以编程方式检查具有给定名称的过滤器是否存在?

我开发了一个指令来处理基于字符串输入的页面内容,如果字符串的某些部分对应于系统中存在的过滤器,我希望它做出不同的反应。 例如,我有一个本地化过滤器:

// Somewhere in the code
var myInput = 'localize';

// Somewhere else
var contentToProcess = 'my content';
var result = '';
if ($filter.hasOwnProperty(myInput))    // TODO: this is the part I'm trying to figure out
    result = $filter(myInput)(contentToProcess);
else
    result = 'something else';

乔纳森(Jonathan)的答案也是可以接受的,但是我想找到一种方法,无需使用try catch就可以检查过滤器是否存在。

您可以查看是否存在这样的过滤器:

return $injector.has(filterName + 'Filter');

'Filter'后缀是在内部通过角度添加的,因此您必须记住添加它,否则将始终返回false

这似乎为我工作。

var getFilterIfExists = function(filterName){
  try {
    return $filter(filterName);
  } catch (e){
    return null;
  }
};

然后,如果检查返回值,则可以执行简单的操作。

// Somewhere in the code
var myInput = 'localize';
var filter = getFilterIfExists(myInput);
if (filter) { // Check if this is filter name or a filter string
  value = filter(value);
}

奖金

如果您想解析过滤字符串,例如'currency:"USD$":0' ,则可以使用以下内容

var value; // the value to run the filter on
// Get the filter params out using a regex
var re = /([^:]*):([^:]*):?([\s\S]+)?/;
var matches;
if ((matches = re.exec(myInput)) !== null) {
    // View your result using the matches-variable.
    // eg matches[0] etc.
    value = $filter(matches[1])(value, matches[2], matches[3]);
}

一起拉

希望有一个更优雅的方法可以使用angular进行此操作,但是似乎没有。

// Somewhere in the code
var myInput = 'localize';
var value; // the value to run the filter on


var getFilterIfExists = function(filterName){
  try {
    return $filter(filterName);
  } catch (e){
    return null;
  }
};
var filter = getFilterIfExists(this.col.cellFilter);
if (filter) { // Check if this is filter name or a filter string
  value = filter(value);
} else {
  // Get the filter params out using a regex
  // Test out this regex here https://regex101.com/r/rC5eR5/2
  var re = /([^:]*):([^:]*):?([\s\S]+)?/;
  var matches;
  if ((matches = re.exec(myInput)) !== null) {
      // View your result using the matches-variable.
      // eg matches[0] etc.
      value = $filter(matches[1])(value, matches[2], matches[3]);
  }
}

您可以这样做:

var filter = $filter(myInput);
if (filter)
    result = filter(contentToProcess);
else
    result = 'something else';

在JS中,未定义和null值被视为false ,因此这应在您的情况下有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM