Angular - Interpolate string with html

心不动则不痛 提交于 2019-11-28 23:45:25

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>

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!