angularjs – 如何在标记中使用条件绑定中的HTML

前端之家收集整理的这篇文章主要介绍了angularjs – 如何在标记中使用条件绑定中的HTML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这样的标记
<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的情况下执行此操作来保留三元运算符?

第一选择

我通过以下方式工作(没有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>
原文链接:https://www.f2er.com/angularjs/142058.html

猜你在找的Angularjs相关文章