How to use HTML inside conditional binding in markup

I have this markup

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

I would like to emphasize There are 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 for this while keeping the ternary operator?

+7
angularjs
source share
1 answer

1st option

I work as follows (without ng-show or ng-if ). I use ng-bind-html and the $ sce service to render HTML. Since your message “without additional notes” is general and widespread, we can easily identify it in the controller and get it from the method after disinfection.

 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> 

Second 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> 
+2
source share

All Articles