如何在Javascript数组中添加HTML标记

时间:2018-06-11 14:00:29

标签: javascript angularjs

我需要在概要的Javascript数组中添加少量HTML。有没有一种方法可以做到这一点,因为它目前以文本形式输出?

到目前为止,我有以下

app.controller('primaryServiceListController', ['$scope', '$http', function($scope, $http){
    $scope.serviceListings = [
        {
            url: "details.html",
            img: "service-01.jpg",
            sector: "Business",
            synopsis: "Completely synergize resource taxing relationships <strong>via premier niche markets</strong>. Professionally cultivate one-to-one customer service robust."
        }
    ]
}]);

3 个答案:

答案 0 :(得分:1)

您需要在应用中加入ngSanitize,然后在模板中,您可以使用ng-bind-html指令轻松绑定HTML:

<div ng-bind-html="serviceListings[0].synopsis"></div>

请参阅以下工作演示:

&#13;
&#13;
angular.module('app', ['ngSanitize'])
  .controller('ctrl', ['$scope', function($scope) {
    $scope.serviceListings = [{
      url: "details.html",
      img: "service-01.jpg",
      sector: "Business",
      synopsis: "Completely synergize resource taxing relationships <strong>via premier niche markets</strong>. Professionally cultivate one-to-one customer service robust."
    }]
  }]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.23/angular-sanitize.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div ng-bind-html="serviceListings[0].synopsis"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以将其添加为文本,然后在html中使用ng-bind-html进行渲染。

<element ng-bind-html="expression"></element>

答案 2 :(得分:0)

您可以将字符串渲染为html,如下所示:

<div ng-bind-html="serviceListings[0].synopsis"></div>

如果需要,您还可以使用$sce创建过滤器并清理数据:

.filter('trustHtml', [
        '$sce',
        function($sce) {
            return function(value) {
                return $sce.trustAs('html', value);
            }
        }
    ]);

并在html文件中使用它

<div ng-bind-html="serviceListings[0].synopsis | trustHtml"></div>