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?
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" .
2: - , , , , . " {{name}}"
:
$compile($scope.row.text)($scope)
, .
, :
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}}
, ...
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 >