如何替换模板中的html角度

时间:2016-11-07 08:44:44

标签: angularjs

我有一个存储数据的变量

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

在html中我带它

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

但是,文本显示没有任何格式,但我希望它像html,如何解决?

4 个答案:

答案 0 :(得分:0)

使用 ng-bind-html =&#34; scopevar&#34;

例如

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

可以找到更多详细信息here

答案 1 :(得分:0)

使用ng-bind-html

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

答案 2 :(得分: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);
                });
            }
        };
    };
})();

它可以用作

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

答案 3 :(得分:0)

基本上要使用ng-bind-html,你需要告诉angular,HTML内容字符串是值得信赖的,你可以在角度文档中引用这个article,所以要在你的JS中添加以下代码

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

但只是这一行会引发一个错误,说明要使用'未知提供商',您需要angular-sanitize.js才能在控制器中注入$sce并在角度中注入ngSanitize模块如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="angularjs@1.5.8" 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>