Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24600

How I make AngularJS to always bind as html even when I am using ``{{..}}`` bind style

I'm getting HTML template, and HTML data from 2 external resources. This is for example of HTML Template

<div>
  {{data}}
</div>

This is the HTML data

<b>Hello World</b>

I want to compile the HTML data, into the HTML template.

I know I can using ng-bind-html, but in my case I cannot change the template I got from external resources. I want that the default bind {{..}} will be as HTML instead of text Is it possible?

In other words: How I make AngularJS to always bind as html even when I am using {{..}} bind style

Upvotes: 0

Views: 74

Answers (2)

Miguel
Miguel

Reputation: 20633

It's not possible to use curly braces to insert HTML to render, However, you can recompile the template with $compile and use ng-bind-html.

Basic example:

HTML

<div ng-app="myApp" ng-controller="MainCtrl">
  <output></output>
</div>

JS

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope, $sce, $compile) {
  var template = '<div>{{data}}</div>';
  template = template.replace(/\{\{(\w+)\}\}/, '<span ng-bind-html="$1"></span>');

    angular.element(document.querySelector('output')).append($compile(template)($scope));
    $scope.data = $sce.trustAsHtml('<b>Hello world</b>');
});

JSFiddle Demo: https://jsfiddle.net/tjruzpmb/250/

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

You cant use html in {{}}

Angular only interpolates those braces as text. Otherwise it would be massively expensive to sanitize and would cause performance issues.

There are numerous other ways to include html also including custom directives and ng-include

Upvotes: 1

Related Questions