在Angularjs中使用json文件中的变量

时间:2016-01-10 12:24:49

标签: angularjs json variables

没有找到任何相关信息。 问题是: 是否可以将变量添加到json文件,然后以下列方式使用它

json文件:

{
  "s1": {
   "text": "Benefit from falling {{ symbol }} prices as well as rising {{ symbol }} prices. Buy or sell instantly"
  }
}

位指示:

 $scope.symbol = 'gold';

查看:

 <p>{{content.s1.title}}</>

我想得到的是:

受益于金价下跌以及金价上涨。立即买入或卖出

感谢您的帮助

3 个答案:

答案 0 :(得分:3)

您应该使用$interpolate

HTML:

angular.module('app', []).
controller('ctrl', function($scope, $interpolate) {
  $scope.content = {
    "s1": {
      "text": "Benefit from falling {{ symbol }} prices as well as rising {{ symbol }} prices. Buy or sell instantly"
    }
  };

  $scope.symbol = 'this is a test';

  $scope.resolveText = function(t) {
    return $interpolate(t)($scope);
  };
});

JS:

resolveText

JSFIDDLE

P.S。 {{1}}可以快速向您展示其工作原理。我认为创建一个封装逻辑的指令会更好。

答案 1 :(得分:1)

您可以使用String.prototype.replace

假设mystr是您的JSON内容的示例。

$scope.symbol = 'gold';
mystr.replace('<symbol>', $scope.symbol);

返回

{
  "s1": {
    "text": "Benefit from falling gold prices as well as rising gold prices. Buy or sell instantly"
  }
}

用法:string.replace(substr|regex, newSubstr|function)

Documentation

答案 2 :(得分:0)

使用$interpolate service

var result = $interpolate("Some string with {{var}}")({var: "Value"});

Example