Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

angularjs - Angular - Interpolate string with html

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...