Angular - 用 html 插入字符串 [英] Angular - Interpolate string with html

查看:40
本文介绍了Angular - 用 html 插入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个看起来像这样的模板字符串":

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

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

我想插入的名称是一个 in 变量.所以我是这样进行的:

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>"
};

但是 html 代码被转义了.知道我如何实现这一目标吗?

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

PS:对于那些想知道为什么我不把字符串放在模板中的人,这是因为我的模板字符串来自服务器.

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.

推荐答案

这个 Plunkr 输出Hello my name is 查克"正如预期的那样.JavaScript 与问题相同.

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

在你的 HTML 中,使用 ng-bind-html 来防止 HTML 被编码.

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>

这篇关于Angular - 用 html 插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆