Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

I'm not sure if this is what you're going for:

http://jsfiddle.net/dMp55/

HTML

<div ng-app="ngAppDemo">
    <div ng-controller="ngAppDemoController">
      I can add: {{a}} + {{b}} =  {{ a+b }}
      <p ng-bind-html-unsafe="myHTML"></p>
    </div>
</div>

JS

angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  $scope.a = 1;
  $scope.b = 2;
  $scope.myHTML = '{{a}}';
});

Output

I can add: 1 + 2 = 3
{{a}}

but I believe you will have to eval or compile the text...

I have solved this by using $templateCache as following:

In Controller:

myApp.controller('RowCtrl', function ($scope, $templateCache) {

    $scope.row = {
       id: 2,
       text: '{{ name }}'
    };

    var row_tmpl = 'row-tmpl-' + row['id'];
    $templateCache.put(row_tmpl, row.text);
    $scope.row_tmpl = row_tmpl;
});

In Template:

  <div ng-include src="row_tmpl" >

  </div >
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top