2016-11-07 75 views
0

我有一个变量存储数据如何在模板角代替HTML

this.storage = { decription: 'text <br> info \n' }; 

在HTML中我把它

<div> {{ ::$ctrl.storage.decription }} </div> 

然而,文本没有任何格式显示出来,但我想它像html一样,如何解决它?

回答

0

基本上使用ng-bind-html知道更多关于这个,你可以参考这个article角文件,所以要添加以下代码在您的JS

$scope.storage.description = $sce.trustAsHtml('text <br> info \n'); 

但仅仅这条线将抛出你的错误说“未知供应商”来使用,你需要有angular-sanitize.js为了注入在控制器$scengSanitize你的角模块中像var app = angular.module('app',['ngSanitize']);

var app = angular.module('app',['ngSanitize']); 
 
app.controller('Ctrl',function($scope,$sce){ 
 
    
 

 
$scope.storage = {}; 
 
    
 
$scope.storage.description = $sce.trustAsHtml('text <br> info \n'); 
 
    
 
    });
<script data-require="[email protected]" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script> 
 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-sanitize.js"></script> 
 

 

 

 

 
<div ng-app="app" ng-controller="Ctrl"> 
 
    
 
    
 
<div ng-bind-html="storage.description"></div> 
 

 
</div>

+0

$ sce.trustAsHtml返回TrustedValueHolderType,但我需要HTML –

+0

你尝试运行该代码段吗?只需按照代码段中的步骤操作即可 –

+0

它的工作,谢谢 –

0

使用纳克绑定-HTML = “scopevar”

例如在

<div ng-bind-html="$ctrl.storage.decription"></div> 

进一步的细节可发现here

+0

我添加到NG-绑定,HTML,但是不行,都走了 –

+0

@ splincodeweb开发商这并不是说这一切都不见了,** $ ctrl.storage.description **可能是摆在首位空。尝试把** storage.description **而不是** $ ctrl.storage.description **。还要确保** storage.description **在** $ scope **中正确初始化为** $ scope.storage.description **,以便** ng-bind-html =“$ scope.storage.description” **按预期显示。 – masterpreenz

+0

它的工作,感谢的 –

0

使用ng-bind-html

<div ng-bind-html="ctrl.storage.description"></div> 
+0

我添加到ng-bind-html,但不工作,全部不见了 –

+0

它的工作,谢谢 –

+0

伟大的帮助。 – masterpreenz

0

你可以使用

this.storage = { decription: $sce.trustAsHtml('text <br> info \n')}; 
and use ng-bind-html 

或写这样的指令,

(function() { 
    'use strict'; 
    angular 
     .module('app') 
     .directive('dynamic', dynamic); 

    dynamic.$inject = ['$compile']; 

    function dynamic($compile) { 
     return { 
      restrict: 'A', 
      replace: true, 
      link: function (scope, ele, attrs) { 
       scope.$watch(attrs.dynamic, function(html) { 
        ele.html(html); 
        $compile(ele.contents())(scope); 
       }); 
      } 
     }; 
    }; 
})(); 

,你需要告诉角度的HTML内容字符串信任它可以使用作为

<div dynamic="$ctrl.storage.decription"></div> 
+0

它的工作,谢谢 –