If my content row.textis ...">

Compiling text in AngularJS

I have the following template:

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

If my content row.textis a string, say:

  Hi your name is {{ name }}

The following is displayed:

  Hi your name is {{ name }}

instead of the actual binding {{ name }}.

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

+3
source share
3 answers

1: After spending some time on this problem, I realized that parsing a string that might contain AngularJS expressions is one way to do this below.

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

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

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

Then you will get the following line in the result variable: Hello my name

.

, , , , "name" .

: AngularJS $

2: - , , , , . " {{name}}"

:

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

: AngularJS $

, .

+3

, :

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}}';
});

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

, ...

0

I solved this using the $templateCachefollowing:

In the 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 the template:

  <div ng-include src="row_tmpl" >

  </div >
0
source

All Articles