0

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:

  • get the input text and bold it;
  • return the changed value in place and make it rendered,

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.

4
  • You're sure you would not be better off using ng-class? Commented Jul 16, 2019 at 9:15
  • Dead sure.This application is made for study purposes. Making it through css, inline styling, getElementBy in js, or ng-class would be too easy :) Commented Jul 16, 2019 at 9:17
  • maybe: stackoverflow.com/questions/20284965/angular-filter-return-html Commented Jul 16, 2019 at 9:25
  • Thanks Miri, it's virtually the same that I have already applied, indeed a good solution. Commented Jul 16, 2019 at 9:40

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this one is best suiting my needs and now everything works as charm!
1

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

3 Comments

But these are impossible to use with <div>{{ person.name|bold }}</div>, right?
this belongs to the comments section I think
<div ng-bind-htm= 'person.name | bold'></div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.