我正在编写一个过滤器,将地址格式化为一行。将传递给筛选器的对象具有以下格式:
{
Line1: "123 Main St.",
Line2: "Apartment 2", // Optional
City: "Chicago",
State: "IL",
Zip: "60623"
}到目前为止,我有以下几点:
angular.module('myApp')
.filter('address', function ($interpolate) {
return function (input, template) {
if (input === null || !angular.isDefined(input)) {
return input;
}
// template is optional. If not provided, use the following
if(!template) {
template = '{{Line1}}, {{Line2 ? Line2 + \', \' : \'\'}}{{City}} {{State}} {{Zip}}';
}
try {
var parsedTemplate = $interpolate(template);
} catch (e) {
console.log(parsedTemplate, template, input, e)
return input;
}
// Compile the template in the context of the input object
return parsedTemplate(input);
};
});在角度1.2,这是很好的工作。但是,在Error: Lexer Error: Unexpected next character at columns 6-6 [?] in expression [Line2 ? Line2 + ', ' : '']. 1.0中,它失败了--我的想法是角1.0不支持三元操作符$interpolated表达式,但是我找不到任何文档表明支持是在角1.2中添加的。
有没有办法在角1.0中使用三元算符,如果没有,我如何才能绕过这个限制呢?
(加分-在文档中提到此更改的地方,还是在角度git中提交的更改?)
发布于 2014-07-01 15:08:31
我意识到,在升级到1.1.5之前,我在插值表达式中使用三元操作符的解决方法是使用&&和|| (如someCondition && TruthyResult || FalseyResult)来有效地获得相同的结果。下面是如何将其应用于您的代码:
template = '{{Line1}}, {{Line2 && (Line2 + \', \') || \'\'}}{{City}} {{State}} {{Zip}}';演示: http://jsfiddle.net/f9n6r/
这个设置的唯一问题是,如果TruthyResult实际上不返回一些真实的东西,那么FalseyResult将被返回(与三元操作符相比,使用&&和||的性质)。但是,在您的代码中,(Line2 + \', \')永远不会因为\', \'而失败,所以这里不会出现问题。但在更一般的情况下,情况可能是这样。
https://stackoverflow.com/questions/24512778
复制相似问题