在AngularJS中显示HTML

9 浏览
0 Comments

在AngularJS中显示HTML

我有一个需要插入HTML标签的angular代码,我发现可以使用ngSanitizehttps://docs.angularjs.org/api/ngSanitize,但我不想在该项目中加载另一个库。我尝试了这个:AngularJS:在视图中呈现$scope变量中的HTML,但是我无法使其工作。有没有办法在不加载另一个angular库的情况下实现这个? \nhtml:\n

  
  • {{procedure.icon}}

    text here: {{procedure.text}} your number is: {{procedure.number}} price you will pay: {{procedure.price}}

\njs:\n

var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
  $scope.procedures = [{
    icon: '',
    text: 'test text',
    number: 1,
    price: 10000
  }];
}

\njsfiddle:\nhttp://jsfiddle.net/wD7gR/247/

0
0 Comments

问题的原因是在AngularJS中显示HTML时遇到困难,解决方法是使用ng-bind-html-unsafe指令。

在实际代码中,你可以按照以下步骤进行操作:

1. 在控制器中定义一个$scope变量,用于存储HTML代码。例如:$scope.html = "<i class='fa fa-american-sign-language-interpreting' aria-hidden='true'></i>";

2. 在HTML模板中使用ng-bind-html-unsafe指令来显示HTML代码。例如:<div ng-bind-html-unsafe="html"></div>

通过这两步操作,你可以在AngularJS应用中显示HTML代码,无论是图标、文本还是其他内容。如果你遇到了问题,可以在评论中提问,我会在接下来的时间里给你编写一个完整的函数。

希望这样的解决方案能够帮助到你,如果有其他问题,请随时提问。

0
0 Comments

好的,我明白了。你可以这样修改你的代码:

首先,在你的app.js文件中插入以下代码:

app.filter('sce', ['$sce', function ($sce) {
    return $sce.trustAsHtml;
}]);

然后,在HTML中使用以下代码:

这样,你的代码就可以正确显示HTML了。希望对你有帮助!

0
0 Comments

问题的原因是在AngularJS的版本1.2.0之后,AngularJS引入了$sce服务,可以用来标记HTML内容为“安全”。解决方法是使用$sce服务的trustAsHtml()方法来标记HTML内容为“安全”。

以下是解决方法的代码示例:

angular.module('myApp',[])
.controller('MyCtrl', function($scope, $sce) {
    $scope.procedures = [
        {
            icon: $sce.trustAsHtml(''),
            text: 'test text',
            number: 1,
            price: 10000
        }
    ];
});


  • text here: {{procedure.text}}

    your number is: {{procedure.number}}

    price you will pay: {{procedure.price}}

感谢您提供的代码,这正是我想要的。但是现在您的代码有问题,在我点击图标之前显示了div。我删除了所有与此主题无关的代码,我相信您能够轻松添加任何显示/隐藏逻辑。无论如何,我已经更新了嵌入的代码片段,通过点击图标来实现显示/隐藏。非常高兴能够帮助您。

0