2

Didn't find anything on this. The question is: Is it possible to add variable to json file and then use it in following way

json file:

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

Contoller:

 $scope.symbol = 'gold';

View:

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

What I want to get is:

Benefit from falling gold prices as well as rising gold prices. Buy or sell instantly

Thank you for your help

3 Answers 3

3

You should use $interpolate for that:

HTML:

<div ng-app="app">
  <div ng-controller="ctrl">
    <div>
      {{resolveText(content.s1.text)}}
    </div>
  </div>
</div>

JS:

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);
  };
});

JSFIDDLE.

P.S. the resolveText is a quick way to show you how this works. I think it's better to create a directive that will encapsulate the logic.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use String.prototype.replace

Example assuming mystr is your JSON content.

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

returns

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

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

Documentation

4 Comments

Right, that what I was thinking about. But the first way is exactly what I was after. Thanks anyway
No problem. Don't forgot to valid the answer if it has solved your problem. And a simple vote for other answers can be a good alternative to say "Good job but can do better".
@chalasr - This is NOT a good way to solve this problem. Do you want to use angularjs or build your own custom framework? Plus, this wont work if the $scope.symbol will change it's value (or do you want to add a watch and run your code?)
It's just a quick way using pure javascript. I know your answer is better because it uses angularjs built-in methods. But what I'm proposing reproduces the same work as your answer, where $scope.resolveText is your watcher and $interpolate your substring replacer. It's just the angularjs way, and thank's for it.
0

Use $interpolate service:

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

Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.