Olaf Erlandsen
Olaf Erlandsen

Reputation: 6036

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

Upvotes: 1

Views: 2322

Answers (2)

Phil
Phil

Reputation: 164813

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

Upvotes: 4

Samuel Toh
Samuel Toh

Reputation: 19278

Update:
Assuming OP has access to ES6. Then try using the standard javascript API, String template.

See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals

Example:

"use strict";
let variable = "mike";
let country = "Australia";
let posts = [
    {
        id:1,
        name: 'bla bla bla',
        content: `Hello, my name is ${variable} and i am from ${country}`
    }
];

console.log(posts);

Note that the string begins and ends with a "`" character vs "

Also example in AngularJS:

JSFiddle

Upvotes: 1

Related Questions