Al-76
Al-76

Reputation: 1878

How can you add HTML markup in a Javascript array

I need to add a small amount of HTML inside part of my Javascript array for the synopsis. Is there a method to do this as currently it outputs as text?

So far I have the below

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."
        }
    ]
}]);

Upvotes: 1

Views: 440

Answers (3)

31piy
31piy

Reputation: 23869

You need to include ngSanitize in your app and then, in your template, you can bind the HTML easily using ng-bind-html directive:

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

Please see the following working demo:

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."
    }]
  }]);
<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>

Upvotes: 1

wobsoriano
wobsoriano

Reputation: 13472

You can render the string as html like this:

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

You can also create a filter and sanitize the data using $sce if you want:

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

And to use it in the html file

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

Upvotes: 0

LucaP
LucaP

Reputation: 718

You can add it as a text and then use ng-bind-html in html to render it.

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

Upvotes: 1

Related Questions