2016-11-21 66 views
2

基本上,我正在做的是从我的服务器请求模板。这是一个简短的例子:AngularJS:使用字符串中的角度变量从范围变量呈现HTML

$scope.template = { 
    'title': 'default', 
    'description': 'default template', 
    'html': '<html><head><style>body {background: red;}</style></head><body>{{data.name}}</body></html>' 
} 

$scope.data = { 
    name: 'John' 
} 

这是我从我的服务器收到的JSON对象。我想把它渲染到DOM中。会显示什么,就是$scope.name中的商店。

我有这个在我的角度

app.filter("trust", ['$sce', function($sce) { 
    return function(htmlCode){ 
    return $sce.trustAsHtml(htmlCode); 
    }; 
}]); 

这在我的HTML

<div ng-bind-html="template.html | trust"></div> 

这使得HTML,但叶{{名}}为{{名}},当它应该说约翰。

+0

我添加了一个https://plnkr.co/edit/5XwTMRTK83KntRP5LE8I?p=preview – nmanikiran

+0

知道更多阅读https://docs.angularjs.org/api/ng/service/$compile – nmanikiran

+1

@ManiKiran谢谢,我用您的解决方案 – notacodemonkey

回答

0

看来你忘了在$ scope.data在单引号把名字,像这样:

$scope.data = { 
    'name' = 'John' 
} 

希望这个作品

+2

如下所述,这是一个错误我简化了问题,而不是实际的代码。我已经更新了这个问题。 – notacodemonkey

3

存储HTML(与角变量)在后端是不好的做法。 您的优先级应该是重构您的后端代码。

如果您没有访问到后端,您可以尝试创建一个使用$编译指令:

$scope.template = $compile('<html><head><style>body {background: red;}</style></head><body>{{data.name}}')($scope); 

你可以做,在一个控制器使用$interpolate还有:

$scope.template = $interpolate('<html><head><style>body {background: red;}</style></head><body>{{data.name}}')($scope); 
+0

我也在构建后端,它在Node中。你会如何建议重构后端代码?为此,我试图快速切换模板。你会用玉之类的东西吗? – notacodemonkey

+0

后端应该只返回数据。格式化完成客户端使用angularjs模板。 – gyc

+0

对,我想将我的模板存储在后端,因为它们应根据用户动态显示。所有这些模板都将显示相同的数据,但只是以不同的格式显示。 – notacodemonkey