Peter Boomsma
Peter Boomsma

Reputation: 9808

Ternary statement with HTML elements

I'm trying to create a ternary statement that also uses HTML elements:

{{vm.showDetails ? <span>asd</span> : <span>red</span> }}

But the browser output is:

{{vm.showDetails ? 'asd' : 'red'}}

If I remove the tags then the ternary statement works fine, is it not possible to use HTML elements inside a ternary statement?

Upvotes: 4

Views: 725

Answers (1)

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

To render such HTML elements, under some condition, you would want either a directive with $compile (since they are responsible for DOM manipulations), or use a hack - ng-bind-html, from ngSanitize module.

Here is an example:

var app = angular.module('myApp', ["ngSanitize"]);
app.controller('myCtrl', function($scope) {
  var vm = this;
  vm.showDetails = true;
});

/* a useful filter for other unsafe HTML elements */
app.filter('trustAsHtml', function($sce) {
  return $sce.trustAsHtml;
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.9/angular-sanitize.js"></script>

<body>
  <div ng-app="myApp" ng-controller="myCtrl as vm">

    <input type="checkbox" ng-model="vm.showDetails" />
    vm.showDetails
    <hr>

    <div ng-bind-html="vm.showDetails ? '<span>asd</span>' : '<span>red</span>'"></div>

  </div>
</body>
</html>

Upvotes: 6

Related Questions