Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HTML inside conditional bind in markup

Tags:

angularjs

I have markup like this

 <p>{{ !job.AdditionalNotes ? "No additional notes." : job.AdditionalNotes }}</p>

Would like to emphasis No Additional notes using something like.

 <p>{{ !job.AdditionalNotes ? <em>"No additional notes."</em> : job.AdditionalNotes }}</p>

Is there a way to do this without using ng-if and ng-show to do this retaining the ternary operator?

like image 889
naveen Avatar asked May 23 '16 11:05

naveen


1 Answers

1st Option

I get this working in the following way (without ng-show or ng-if). I'm using ng-bind-html and $sce service to render the HTML. Since your "no additional notes" message is generic and common, we can easily define in the controller and get it from a method after sanitization.

var app = angular.module("sa", []);

app.controller("FooController", function($scope, $sce) {

  $scope.jobs = [{
    name: "Sr. Software Developer"
  }, {
    name: "Software Associates",
    AdditionalNotes: "Remote location"
  }, {
    name: "Front-end developer"
  }];

  $scope.trust = function(text) {
    return $sce.trustAsHtml(text);
  };

  $scope.noNotesMessage = function() {
    return $scope.trust("<em>No additional notes.</em>")
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="FooController">
  <ol>
    <li ng-repeat="job in jobs">
      <strong>{{job.name}}</strong>
      <p ng-bind-html="!job.AdditionalNotes ? noNotesMessage() : trust(job.AdditionalNotes)"></p>
    </li>
  </ol>
</div>

2nd Option

Alternatively, you can write a directive:

var app = angular.module("sa", []);

app.controller("FooController", function($scope, $sce) {

  $scope.jobs = [{
    name: "Sr. Software Developer"
  }, {
    name: "Software Associates",
    AdditionalNotes: "Remote location"
  }, {
    name: "Front-end developer"
  }];
});

app.directive('notes', function() {
  return {
    restrict: 'E',
    scope: {
      additional: '='
    },
    link: function($scope, element, attr) {
      var html = "<p>" + ($scope.additional || "<em>No additional notes.</em>") + "</p>";
      element.html(html);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="FooController">
  <ol>
    <li ng-repeat="job in jobs">
      <strong>{{job.name}}</strong>
      <notes additional="job.AdditionalNotes"></notes>
    </li>
  </ol>
</div>
like image 100
Shashank Agrawal Avatar answered Nov 08 '22 09:11

Shashank Agrawal