允许在Angular控制器或视图中使用html标记

Allow html tags in Angular controller or view

本文关键字:html 标记 视图 Angular 控制器      更新时间:2023-09-26

我的控制器:

LandingApp.controller('LandingCtrl2', function($scope){
    $scope.articles = [
        {
            'imageSrc'   : IMG_DIR + 'spec9.jpg',
            'title'      : 'Stencils',
            'description': 'Plastic or thin metal stencils.<br/>100% Custom made'
        }
    ];
});

当我尝试在我的ng repeat(…文章中的文章…){{article.description}}我得到了... stencils.<br/>100% ....,但我需要换行符或其他一些html标记。我该如何解决这个问题?

您需要创建一个方法,该方法可以告诉AngularJS将该字符串呈现为HTML

示例:

$scope.renderHtml = function (htmlCode) {
    return $sce.trustAsHtml(htmlCode);
}

在你的view:

<div ng-bind-html="renderHtml(article.description)"></div>

不要忘记在控制器中包含$sce

LandingApp.controller('LandingCtrl2', function($scope,$sce){ ...