【问题标题】:Change specific words of string to bold将字符串的特定单词更改为粗体
【发布时间】:2014-11-05 01:13:52
【问题描述】:

我的页面中有一个 span 元素。我将单词连接到 AngularJS 中的单个变量,然后将变量引用到页面中的 span 元素。

$scope.abc = "Downstream";
$scope.abc.concat('<b>','Upstream',</b>);

查看页面时显示Downstream&lt;b&gt;Upstream&lt;/b&gt;

如何用粗体单独显示Upstream这个词?

【问题讨论】:

标签: javascript html angularjs


【解决方案1】:

据此https://docs.angularjs.org/api/ng/directive/ngBindHtml

您需要包含 ngBindHtml 和 $sanitize 服务

在你的js文件中,应该是

angular.module('App', ['ngSanitize'])
  .controller('Ctr', ['$scope', function($scope) {
     $scope.abc = "Downstream";
     $scope.abc2 = $scope.abc.concat('<b>','Upstream','</b>');
}]);

在你的html文件中,应该是

<div ng-controller="Ctr">
    <p ng-bind-html="abc2"></p>
</div>

【讨论】:

    【解决方案2】:

    似乎与angular variable generating html 重复。

    我不知道角度,但阅读那篇文章很容易。做吧:

     $scope.abc = $scope.trustAsHtml($scope.abc);
    

    HTML

    <div data-ng-bind-html="abc "></div>     
    

    还要检查您的 Angular 版本,对于 1.2 或更低版本,您可以使用 ng-bind-html-unsafe 绑定。

    <div class="post-content" ng-bind-html-unsafe="abc"></div>
    

    根据TheSharpieOne 的评论,这在 Angular 1.2+ 中不再起作用:

    “已被严格上下文转义替换。见docs.angularjs.org/api/ng.$sce

    【讨论】:

    • ns-sanitize 也必须包括在内。感谢您的回答!
    猜你喜欢
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2013-09-15
    相关资源
    最近更新 更多