Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling text in AngularJS

I have following template:

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

If the content of my row.text is a string say:

  Hi your name is {{ name }}

It will display:

  Hi your name is {{ name }}

instead of the actual {{ name }} binding.

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

like image 598
Kok Hoor Chew Avatar asked May 11 '26 09:05

Kok Hoor Chew


1 Answers

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:

$compile($scope.row.text)($scope)

Reference: AngularJS $compile

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

like image 114
Kok Hoor Chew Avatar answered May 14 '26 00:05

Kok Hoor Chew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!