Search code examples
angularjsangularjs-ng-repeat

Add html to json content in an NG-Repeat


Im repeating objects of JSON using NG-Repeat. How do I include html, such as a link, in here:

        {id: "53",  description: "here is a <a href = '#/detail/'>Link</a> to something", additional: ["2.jpg", "3.jpg" ]}

Solution

  • You need to use $sce to trust the HTML. I like to create a filter and use ng-bind-html on a <span> tag. Using a filter makes it super simple to show HTML wherever you need. Here is a simple example.

    angular.module('app', [])
      .filter('unsafe', ($sce) => {
        return function(value) {
          return $sce.trustAsHtml(value);
        }
      })
      .controller('ctrl', ($scope) => {
        $scope.items = [{
            id: "53",
            description: "here is a <a href = '#/detail/'>Link</a> to something",
            additional: ["2.jpg", "3.jpg"]
          },
          {
            id: "54",
            description: "here is another <a href = '#/detail/'>Link</a> to something",
            additional: ["4.jpg", "5.jpg"]
          }
        ];
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
    <div ng-app="app" ng-controller="ctrl">
      <ul>
        <li ng-repeat="item in items"><span ng-bind-html="item.description | unsafe"></span></li>
      </ul>
    </div>