15

So i've got a "template string" that looks like this:

var templateString = "Hello my name is {{name}}";

The name that I want to interpolate is a in variable. So I proceeded this way:

var miniScope = {
 name: "Chuck"
};

var sentence = $interpolate(templateString)(miniScope);
/* sentence: "Hello my name is Chuck" */

This works. Now I'd like to bold the name. I've obviously tried:

var miniScope = {
 name: "<strong>Chuck</strong>"
};

But the html code gets escaped. Any idea how I can achieve this?

PS: For those of you who wonder why I don't just put the string in the template, it's because my template string is coming from the server.

2 Answers 2

16

This Plunkr outputs "Hello my name is Chuck" as expected. The JavaScript is unchanged from the question.

var app = angular.module("app", ["ngSanitize"]);
app.controller("TestCtrl", TestCtrl);
function TestCtrl($scope, $interpolate) {
  var templateString = "Hello my name is {{name}}";

  var miniScope = {
    name: "<strong>Chuck</strong>"
  };

  $scope.sentence = $interpolate(templateString)(miniScope);
}

And in your HTML, make use you use ng-bind-html to keep the HTML from being encoded.

  <body ng-controller="TestCtrl">
    <div ng-bind-html="sentence"></div>
  </body>
Sign up to request clarification or add additional context in comments.

1 Comment

@PardeepJain No, ng-bind-html doesn't work in Angular 2. You need to use [innerHTML] as mentioned in this answer.
1

use this directive to compile stuff from the string.

.directive('compile', ['$compile', function ($compile) {
return function(scope, element, attrs) {
    scope.$watch(
        function(scope) {
            return scope.$eval(attrs.compile);
        },
        function(value) {
            element.html(value);
            $compile(element.contents())(scope);
        }
    );
};
}])


$scope.name = "Vladimir";
$scope.str = "Hello my name is <strong>{{name}}</strong>";


<div compile="str"></div>

and use $sce to compile trusted html if You need Angular $sce doc

but all of this stuff not angular way actualy, You have to use some different partials and include it with ng-include directive.

1 Comment

I actually ended up doing this in a completely different way. I'll leave the post in case this helps someone else. Thanks for your reply

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.