差异$ AngularJS 1.0和1.2之间的插值
我在一行写一个过滤器,以格式的地址。将传递到过滤器的对象的格式为:
I'm writing a filter to format addresses in a single line. The object that will be passed into the filter has the format:
{
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角这工作正常。然而,在角1.0它失败,出现错误错误:词法错误:在6-6列意外的下一个字符前pression [2号线[?]? 2号线+',':'']
我的想法是角1.0不支持三元运算符 $插值
D EX pressions ,但我找不到在角1.2加入的任何文件表明支持。
In Angular 1.2 this works fine. However, in Angular 1.0 it fails with the error Error: Lexer Error: Unexpected next character at columns 6-6 [?] in expression [Line2 ? Line2 + ', ' : ''].
My thought is Angular 1.0 doesn't support the ternary operator $interpolate
d expressions, but I couldn't find any documentation suggesting that support was added in Angular 1.2.
有没有使用角1.0三元运算符的方式,如果没有我怎样才能解决这个限制得到什么?
Is there a way to use the ternary operator in Angular 1.0, and if not how can I get around that restriction?
(加分 - 文档在没有提到这种变化,或提交的角混帐回购协议所做的更改)
(Bonus points - where in the documentation does it mention this change, or which commit in the Angular git repo made the change?)
我意识到,之前我升级到1.1.5,我的解决方法在插值前pressions使用三元运算符是使用&功放;&安培;
和 ||
(如 someCondition和放大器;&安培; TruthyResult || FalseyResult
)以有效地获得相同的结果。这里是你如何把它们运用到你的code:
I realized that before I upgraded to 1.1.5, my workaround to using a ternary operator in interpolated expressions was to use &&
and ||
(like someCondition && TruthyResult || FalseyResult
) to effectively get the same result. Here's how you'd apply it to your code:
template = '{{Line1}}, {{Line2 && (Line2 + \', \') || \'\'}}{{City}} {{State}} {{Zip}}';
DEMO: http://jsfiddle.net/f9n6r/
与此设置唯一的问题是,如果在 TruthyResult
实际上并没有返回的东西truthy,在 FalseyResult
将返回(使用的只是自然&放大器;&安培;
和 ||
这样,相比三元运算符)。在您的code虽然,(2号线+ \\',\\')
绝不会因为falsey的 \\',\\'
,所以它不会是一个问题在这里。但在更一般的情况下,也可能是
The only problem with this setup is if the the TruthyResult
doesn't actually return something truthy, the FalseyResult
will be returned (just the nature of using &&
and ||
like this, compared to the ternary operator). In your code though, (Line2 + \', \')
will never be falsey because of the \', \'
, so it won't be a problem here. But in a more general case, it could be.