How to display an array with html content without ng-repeat? AngularJS

1.3k views Asked by At

I have this

"items" : ["<p>Item 1</p>","<span>Item 2</span>"]

I would like this

<div id="container">
    <p>Item 1</p>
    <span>Item 2</span>
</div>

How can I do it without using ng-repeat ?

2

There are 2 answers

0
Yosvel Quintero On

In AngularJS you can use the ng-bind-html directive to print html and for that you must include the $sanitize service.

Now, to pass the array as an html string to the view you can use Array.prototype.join():

angular
  .module('App', ['ngSanitize'])
  .controller('AppController', ['$scope', function ($scope) {
    var obj = {
      "items": ["<p>Item 1</p>","<span>Item 2</span>"]
    };
    $scope.items = obj.items.join('');
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.10/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.10/angular-sanitize.min.js"></script>

<div ng-app="App" ng-controller="AppController">
  <div id="container" ng-bind-html="items"></div>
</div>

0
Manikandan Velayutham On

You can use directly like this..

$scope.itemNames = {"items" : ["<p>Item 1</p>","<span>Item 2</span>"]};

     <div ng-bind-html-unsafe="itemNames.items"> </div>

or else

use $sce.

.controller('ctrl', ['$scope', '$sce', function ($scope, $sce) {
   $scope.itemNames = {"items" : ["<p>Item 1</p>","<span>Item 2</span>"]};
   $scope.newNames= $sce.trustAsHtml($scope.itemNames.items);
  }]);

  <div ng-bind-html="newNames"> </div>