How to allow the execution of html tags from a variable in angular?

3

I'm consuming data from an api using angular, api is returning the following value with HTML:

variavel = '<p>testo de retorno</p>';

When I make the view in the view type {{variable}} is interpreted as string displaying the HTML. I need to display only the text considering the HTML tags, ie I can not remove the HTML. You have to display only the text and interpret the HTML.

Does anyone know how I can do this using angular?

    
asked by anonymous 29.09.2016 / 16:23

2 answers

2

Use ngBindHtml, in the example just below the contents of the $scope.myHtml variable will be injected into <div> .

HTML

<div ng-app="myApp" ng-controller="myCtrl">
    <div ng-bind-html="myHtml"></div>
</div>

Controller

var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myHtml = '<p>testo de retorno</p>';
});

If you need the practical example to clarify: link

    
29.09.2016 / 20:04
1

As I'm getting the data via Ajax if I try to view the information directly from the ng-bind-html directive, an error is reported for $ sce " Error: [$ sce: unsafe] http://errors.angularjs.org/1.5.5/$sce/unsafe ". So I was able to solve the problem in the following way according to the reference: Angled Problem 1.5 Running with Minimized Files

const angular = require('angular');
const ngRoute = require('angular-route');   

class ProdutoController{
        /* ngInject */
        constructor($scope,$routeParams, $sce){
          this.$scope = $scope;
          this.$sce = $sce;
          this.$routeParams = $routeParams;

        }

        $onInit() {
          this.produto = [];

        }

        $onInit() {
          this.produto = [];
          this.carregaProduto();

        }

        async carregaProduto() {
          const produto = await Promise.all([this.services.produto.get(this.$routeParams.id)]);
          this.$scope.descricao_produto = this.$sce.trustAsHtml(produto.descricao);

          this.$scope.$apply(() => {
            this.produto = produto;
          });


        }

    }

Resolution line:

this.$scope.descricao_produto = this.$sce.trustAsHtml(produto.descricao);

HTML

<div ng-bind-html="descricao_produto"></div>
    
29.09.2016 / 20:22