简体   繁体   English

不使用DOM选择器将AngularJS html文本加粗

[英]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. 我正在编写一个自定义AngularJS过滤器,以在前端使用粗体显示文本元素。 As a generic filter, I do not want to tie it to specific elements, so document.getElementsBy is not a solution. 作为通用过滤器,我不想将其绑定到特定元素,因此document.getElementsBy不是解决方案。 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; 我没有使用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: 在html中:

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

I get <b>Test1</b> in front, instead of having the bolded text. 我得到<b>Test1</b>在前面,而不是加粗的文本。 An advice in which direction should I move is appreciated. 我应该朝哪个方向发展的建议值得赞赏。

The return value is string-raw-value. 返回值是字符串原始值。 you should change the value into html.such as the ng-bind-html and ng-bind. 您应该将值更改为html。,例如ng-bind-html和ng-bind。

You can use a combination of $sce.trustAsHtml and ng-bind-html to accomplish this: 您可以结合使用$sce.trustAsHtmlng-bind-html来完成此操作:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM