2014-12-04 51 views
8

所以我已經患上了「模板字符串」,看起來像這樣:角 - 插值字符串HTML

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

,我想插名,是在變化的。所以我這樣做:

var miniScope = { 
name: "Chuck" 
}; 

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

這個工程。現在我想加粗這個名字。我明顯地嘗試過:

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

但是html代碼被轉義了。任何想法如何我可以實現這一目標?

PS:對於那些想知道爲什麼我不只是將字符串放入模板的人,這是因爲我的模板字符串來自服務器。

回答

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> 

和使用$ SCE編譯值得信賴的HTML,如果你需要Angular $sce doc

這個東西,但都沒有棱角的方式actualy,你必須使用一些不同的諧音,並附NG-include指令。

+1

我實際上最終以完全不同的方式做了這件事。我會離開這個帖子以防別人幫忙。感謝您的回覆 – MonsieurNinja 2014-12-04 12:29:52

11

This Plunkr outputs「Hello your name is Chuck」as expected。 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); 
} 

而在你的HTML中,使用你使用ng-bind-html來保持HTML編碼。

<body ng-controller="TestCtrl"> 
    <div ng-bind-html="sentence"></div> 
    </body> 
+0

是'ng-bind-html'與angular2一起工作嗎? – 2016-07-09 06:22:23