Reputation: 3630
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"
}
I have the following so far:
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);
};
});
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.
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?)
Upvotes: 0
Views: 130
Reputation: 50905
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/
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.
Upvotes: 1