Cheshire Katzzze
Cheshire Katzzze

Reputation: 127

Bold an AngularJS html text without using DOM selectors

I am writing a custom AngularJS filter to use in front-end to bold the text elements. As a generic filter, I do not want to tie it to specific elements, so document.getElementsBy is not a solution. To my understanding, i need to:

The question is what possibilities do I have to get it done? I do not have an element to use element.innerHTML = content;. How can I get the element dynamically to later on apend it?

My filter:

angular.module('TestModule')
    .filter('bold', ['$filter', function ($filter) {
        return function (input) {
            console.log(input.bold());
            // code

            return input.bold();
        };
    }]);

in html:

<div>{{ person.name|bold }}</div>

I get <b>Test1</b> in front, instead of having the bolded text. An advice in which direction should I move is appreciated.

Upvotes: 0

Views: 895

Answers (2)

JoshG
JoshG

Reputation: 6735

You can use a combination of $sce.trustAsHtml and ng-bind-html to accomplish this:

angular.module('app', [])

  .controller('MainController', function($scope) {
    $scope.word = "Test";
  })

  .filter("bold", ['$sce', function($sce) {
    return function(val) {
      return $sce.trustAsHtml(`<b>${val}</b>`);
    };
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MainController">
    Word : {{ word }}<br/> Bold Word: <span ng-bind-html="word | bold"></span>
  </div>
</div>

Upvotes: 1

astonTY
astonTY

Reputation: 59

The return value is string-raw-value. you should change the value into html.such as the ng-bind-html and ng-bind.

Upvotes: 1

Related Questions