首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >$interpolate在AngularJS 1.0和1.2中的差异

$interpolate在AngularJS 1.0和1.2中的差异
EN

Stack Overflow用户
提问于 2014-07-01 14:27:54
回答 1查看 126关注 0票数 0

我正在编写一个过滤器,将地址格式化为一行。将传递给筛选器的对象具有以下格式:

代码语言:javascript
复制
{
  Line1: "123 Main St.",
  Line2: "Apartment 2", // Optional
  City: "Chicago",
  State: "IL",
  Zip: "60623"
}

到目前为止,我有以下几点:

代码语言:javascript
复制
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中提交的更改?)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-01 15:08:31

我意识到,在升级到1.1.5之前,我在插值表达式中使用三元操作符的解决方法是使用&&|| (如someCondition && TruthyResult || FalseyResult)来有效地获得相同的结果。下面是如何将其应用于您的代码:

代码语言:javascript
复制
template = '{{Line1}}, {{Line2 && (Line2 + \', \') || \'\'}}{{City}} {{State}} {{Zip}}';

演示: http://jsfiddle.net/f9n6r/

这个设置的唯一问题是,如果TruthyResult实际上不返回一些真实的东西,那么FalseyResult将被返回(与三元操作符相比,使用&&||的性质)。但是,在您的代码中,(Line2 + \', \')永远不会因为\', \'而失败,所以这里不会出现问题。但在更一般的情况下,情况可能是这样。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24512778

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档