简体   繁体   English

如何在模板Angular中替换HTML

[英]How replace html in template angular

I have a variable that stores data 我有一个存储数据的变量

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

In html I bring it 在HTML中,我把它

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

However, the text is displayed without any formatting, but I would like it to be like html, how to fix it? 但是,显示的文本没有任何格式,但是我希望它像html一样,如何解决?

Use ng-bind-html="scopevar" 使用ng-bind-html =“ scopevar”

in example: 例如:

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

further details can be found here 可以在这里找到更多详细信息

使用ng-bind-html

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

either you can use 要么你可以使用

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

or write a directive for this, 或为此编写指令,

(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);
                });
            }
        };
    };
})();

and it can use as 它可以用作

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

Basically to use ng-bind-html you need to tell angular that the HTML content string is trusted to know more about this you can refer this article in angular docs,so to that add below code in your JS 基本上,要使用ng-bind-html您需要告诉angular值得信任的HTML内容字符串,您可以在angular文档中引用此文章 ,以便在JS中添加以下代码

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

But simply this line will throw you an error saying 'unknown provider' to use that you need to have angular-sanitize.js in order to inject $sce in your controller and ngSanitize in your angular module like var app = angular.module('app',['ngSanitize']); 但是简单的这一行会向您抛出一条错误消息,说``未知提供者''来使用它,您需要拥有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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM