Olaf Erlandsen Olaf Erlandsen - 3 months ago 6
AngularJS Question

How i can parse or evaluate string with variables in AngularJS?

Well, i have a object like to:

$scope.variable = "mike";
$scope.country = "...";
$scope.posts = [
...
{
id:1,
name: 'bla bla bla',
content: 'Hello, my name is {{variable}} and i am from {{country}}'
},
...
];


So, how i can evaluating or parse
content
property?

My idea is used it in my view like this:

<a ng-click=" variable = 'John' ">Change name here!</a>
<div ng-repeat="post in posts">
<h1>{{post.name}}</h1>
<p>{{post.content}}</p>
</div>


Thanks

Answer

Create a method in your controller that allows you to run the string through $interpolate, ie

// don't forget to inject the $interpolate service

$scope.parseContent = function(template) {
    return $interpolate(template)($scope);
};

Then you can use

<p>{{parseContent(post.content)}}</p>

http://plnkr.co/edit/KB0aHsaoCxZGp3DY7JMI?p=preview