我正在编写一个自定义 AngularJS 过滤器,用于在前端将文本元素加粗。作为通用过滤器,我不想将其绑定(bind)到特定元素,因此 document.getElementsBy
不是一个解决方案。据我了解,我需要:
- 获取输入文本并加粗;
- 返回更改后的值并使其呈现,
问题是我有什么可能性来完成它?我没有可以使用的元素element.innerHTML = content;
。如何动态获取元素以便稍后追加它?
我的过滤器:
angular.module('TestModule')
.filter('bold', ['$filter', function ($filter) {
return function (input) {
console.log(input.bold());
// code
return input.bold();
};
}]);
在 html 中:
<div>{{ person.name|bold }}</div>
我得到<b>Test1</b>
在前面,而不是粗体文本。感谢您对我应该朝哪个方向发展的建议。
最佳答案
您可以结合使用 $sce.trustAsHtml
和 ng-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>
关于javascript - 在不使用 DOM 选择器的情况下将 AngularJS html 文本加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053673/