我有这样的标记
<p>{{ !job.AdditionalNotes ? "No additional notes." : job.AdditionalNotes }}</p>
想强调No Additional notes使用类似的东西.
<p>{{ !job.AdditionalNotes ? <em>"No additional notes."</em> : job.AdditionalNotes }}</p>
有没有办法在不使用ng-if和ng-show的情况下执行此操作来保留三元运算符?
第一选择
原文链接:https://www.f2er.com/angularjs/142058.html我通过以下方式工作(没有ng-show或ng-if).我正在使用ng-bind-html和$sce服务来呈现HTML.由于您的“无附加说明”消息是通用且通用的,因此我们可以在控制器中轻松定义并在清理后从方法中获取它.
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>
第二选择
或者,您可以编写指令:
var app = angular.module("sa",{ 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>