0

This jsFiddle explains it all

My code separates hashtags, e.g., #riots = <span class="hashtags">#riots</span> but it's being printed as plaintext instead of html. What am I doing wrong?

function formCtrl($scope){
    $scope.$watch(function() {
        $scope.description = "Wow, it's crazy over here! #baltimore #riots";
      $scope.vidTags = $scope.description.match(/(^|\s)(#[a-z\d-]+)/ig);   
      $scope.desc = $scope.description.replace(/(^|\s)(#[a-z\d-]+)/ig, "$1<span class='hashtag'>$2</span>");
    })
}
#description {
    width: 300px;
    height: 3em;
}
.hashtag {
    color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="formCtrl">
    <textarea ng-model="description" id="description"></textarea>
    <br />
vidTags: {{vidTags}}
    <br />
desc: {{desc}}
    <br />

</div>
Des Horsley
  • 1,858
  • 20
  • 43
Jay
  • 57
  • 1
  • 1
  • 6

2 Answers2

0

You now have to use $sce to run your output through a filter, which you can specify to allow the HTML.

We can implement this using $sce.trustAsHtml() by adding a filter to [the] code (outside of the controller). This custom filter will make sure that [the] HTML doesn’t get filtered out by AngularJS 1.2/AngularJS 1.3 or later

Sources:

http://creative-punch.net/2014/04/preserve-html-text-output-angularjs/ https://docs.angularjs.org/api/ng/service/$sce

James Wilkins
  • 6,836
  • 3
  • 48
  • 73
0

Here's a Plunker that shows a working example using $sce.

http://plnkr.co/edit/sZliFJjOTiRyFxe7Bdts?p=preview

<html>

<head>
  <script data-require="jquery@*" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>

  <script data-require="angular.js@1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="myApp">
  <div ng-controller="formCtrl">
    <textarea ng-model="description" id="description"></textarea>
    <br />vidTags: {{vidTags}}
    <br /><div ng-bind-html="desc"></div>
    <br />
  </div>
  <script>
    var app = angular.module('myApp', []); 
    app.controller('formCtrl', function formCtrl($scope, $sce) {

      $scope.$watch(function() {
        $scope.description = "Wow, it's crazy over here! #baltimore #riots";
        $scope.vidTags = $scope.description.match(/(^|\s)(#[a-z\d-]+)/ig);
        var message = $scope.description.replace(/(^|\s)(#[a-z\d-]+)/ig, '$1<span class="hashtag">$2</span>');
        $scope.desc = $sce.trustAsHtml(message); 
      })
    })
  </script>
</body>

</html>
jake
  • 1,027
  • 8
  • 9
  • @jake where possible try include the code for the answer in your response instead of third party locations, that way if your code gets removed from plnkr in years to come, stack overflow users still get to benefit from your answer. – Des Horsley May 01 '15 at 04:49