Kok Hoor Chew Kok Hoor Chew - 5 months ago 7
Javascript Question

Compiling text in AngularJS

I have following template:

<h1 class="text-center" ng-bind-html="row.text"></h1>

If the content of my
is a string say:

Hi your name is {{ name }}

It will display:

Hi your name is {{ name }}

instead of the actual
{{ name }}

Do I need to eval or compile this row.text expression?


1: After spending some time on the issue, I figured out that parse a string that can possibly contain AngularJS expressions, one way to do is below.

Say your $scope is: { "name": "my name" }

And your string expression is in variable v: var v = "Hello, {{ name }}"

var exp = $interpolate(v);
var result = exp($scope);

You will then get the following string in the result variable: Hello, my name

I will then inject the answer into the scope variable.

However, one issue with this is, once this is done, the result is a string, and therefore any changes to the "name" variable in the scope will no longer affect that particular evaluated expression.

Reference: AngularJS $interpolate

2: If data binding is still important, what I did was instead of doing indirection like that, create a custom template string instead e.g. "Hello {{ name }}"

and compile it accordingly:


Reference: AngularJS $compile

I tried both in a directive and it is working now.