Angular - 使用html插入字符串

Mon*_*nja 10 string-interpolation angularjs

所以我有一个"模板字符串",如下所示:

var templateString = "Hello my name is {{name}}";
Run Code Online (Sandbox Code Playgroud)

我要插入的名称是变量.所以我这样做了:

var miniScope = {
 name: "Chuck"
};

var sentence = $interpolate(templateString)(miniScope);
/* sentence: "Hello my name is Chuck" */
Run Code Online (Sandbox Code Playgroud)

这有效.现在我想大胆一下这个名字.我显然已经尝试过:

var miniScope = {
 name: "<strong>Chuck</strong>"
};
Run Code Online (Sandbox Code Playgroud)

但是html代码被转义了.知道我怎么能做到这一点?

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

Kev*_*son 13

这个Plunkr按预期输出"Hello my name is Chuck ".JavaScript没有改变.

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);
}
Run Code Online (Sandbox Code Playgroud)

在您的HTML中,您可以使用它ng-bind-html来防止HTML被编码.

  <body ng-controller="TestCtrl">
    <div ng-bind-html="sentence"></div>
  </body>
Run Code Online (Sandbox Code Playgroud)

  • @PardeepJain不,`ng-bind-html`在Angular 2中不起作用。您需要使用[this](/sf/answers/3269825821/)答案中提到的`[innerHTML]` 。 (2认同)

Vla*_*nko 1

使用此指令从字符串编译内容。

.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>
Run Code Online (Sandbox Code Playgroud)

如果您需要Angular $sce 文档,请使用 $sce 编译受信任的 html

但所有这些东西实际上并不是有角度的,你必须使用一些不同的部分并将其包含在 ng-include 指令中。