Difference in $interpolate between AngularJS 1.0 and 1.2

匆匆过客 提交于 2019-12-25 03:27:19

问题


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 $interpolated 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?)


回答1:


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.



来源:https://stackoverflow.com/questions/24512778/difference-in-interpolate-between-angularjs-1-0-and-1-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!