【问题标题】:AngularJS and angular-translate: Using the translate filter in an object literalAngularJS 和 angular-translate:在对象文字中使用翻译过滤器
【发布时间】:2014-06-21 13:05:41
【问题描述】:

我有一个 Angular JS 应用程序,它为 i18n 使用 angular-translate。这个应用程序还使用 highcharts.js 显示图表。我在 highcharts-ng 之上构建了一个自定义指令,它允许我将对象文字作为表达式传递,然后用于配置图表的轴:

angular.module('myApp')
  .directive('xxChart', function() {
    return {
      transclude: true,
      template: '<highchart id=id config=config ng-transclude>',
      restrict: 'E',
      scope: {
        id: '=',
        title: '=',
        xxXAxis: '=',
        xxYAxis: '='
      },
      controller: function($scope) {
        $scope.config = {
          options: {
            chart: {
              lineWidth: 10
            },
            xAxis: $scope.xxXAxis,
            yAxis: $scope.xxYAxis,
            plotOptions: {
              spline: {
                lineWidth: 3
              },
              area: {
                lineWidth: 3
              }
            }
          },
          series: [],
          title: {
            text: $scope.title
          }
        };

        this.addSeries = function(name) {
          var series = {
            name: name,
            data: []
          };
          $scope.config.series.push(series);
          return series;
        };
      }
    };
  });

我使用这样的指令:

<xx-chart xx-x-axis="{title: {text: 'My x axis'}}">
...
</xx-chart>

现在我想翻译我的应用程序。我注意到这显然行不通:

<xx-chart xx-x-axis="{title: {text: 'My x axis' | translate}}">
...
</xx-chart>

有没有办法在对象文字中使用翻译过滤器?如果没有,我应该如何在坚持角度架构的同时解决我的问题?

另外请注意,我不能以中断传递包含其他非翻译字段的对象文字的方式更改指令的语义。

这里的最小示例小提琴:http://jsfiddle.net/Ssn53

【问题讨论】:

    标签: angularjs highcharts angularjs-filter angular-translate angular-directive


    【解决方案1】:

    我遇到了同样的问题,发现正确的语法是:

    busy-tracker="{message:('messageId'|translate)}"
    

    注意包含值的大括号。在我的情况下,我不需要将整个表达式括起来的双花括号,因为它是由指令插值的(通过使用私有范围和“&”赋值)。

    【讨论】:

      【解决方案2】:

      使用角度插值应该可以满足您的要求:

      <xx-chart xx-x-axis="{title: {text: {{'My x axis' | translate}} }}">
      ...
      </xx-chart>
      

      注意双花括号 {{ }}

      【讨论】:

      • 不,这给了我:Error: [$parse:syntax] Syntax Error: Token ''My x axis'' is unexpected, expecting [:] at column 18 of the expression [{title: {text: {{'My x axis' | translate}} }}] starting at ['My x axis' | translate}} }}].。据我了解,属性内容已作为表达式进行评估,但未在对象文字内部执行插值。
      • 你能用你的代码发布一个 jsfiddle 或一个 plunker。如果我能玩它,对我来说会更容易。你能确认一下,这是一个错字xqXAxis: '='xqYAxis: '=',而在你的指令的属性中你使用xx-x-axisxx-y-axis vs xq-x-axis and xq-y-axis`。
      • 是的,这是一个错字。 jsfiddle.net/Ssn53 是我正在尝试做的一个最小的,如果有点荒谬的例子。
      • 并非如此。我最终编写了一个遍历对象层次结构并尝试用翻译替换它遇到的所有字符串的函数。然后,我为在每次更改时调用此函数的指令添加了一个模型监视。
      猜你喜欢
      • 2015-08-31
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      • 1970-01-01
      • 2016-05-15
      相关资源
      最近更新 更多