【问题标题】:How to display an array with html content without ng-repeat? AngularJS如何在没有 ng-repeat 的情况下显示包含 html 内容的数组? AngularJS
【发布时间】:2016-12-17 12:27:39
【问题描述】:

我有这个

"items" : ["<p>Item 1</p>","<span>Item 2</span>"]

我想要这个

<div id="container">
    <p>Item 1</p>
    <span>Item 2</span>
</div>

不使用 ng-repeat 怎么办?

【问题讨论】:

    标签: javascript angularjs ng-repeat ng-bind-html


    【解决方案1】:

    你可以这样直接使用..

    $scope.itemNames = {"items" : ["<p>Item 1</p>","<span>Item 2</span>"]};
    
         <div ng-bind-html-unsafe="itemNames.items"> </div>
    

    否则

    使用 $sce。

    .controller('ctrl', ['$scope', '$sce', function ($scope, $sce) {
       $scope.itemNames = {"items" : ["<p>Item 1</p>","<span>Item 2</span>"]};
       $scope.newNames= $sce.trustAsHtml($scope.itemNames.items);
      }]);
    
      <div ng-bind-html="newNames"> </div>
    

    【讨论】:

      【解决方案2】:

      在 AngularJS 中,您可以使用 ng-bind-html 指令来打印 html,为此您必须包含 $sanitize 服务。

      现在,要将数组作为 html 字符串传递给视图,您可以使用 Array.prototype.join():

      angular
        .module('App', ['ngSanitize'])
        .controller('AppController', ['$scope', function ($scope) {
          var obj = {
            "items": ["<p>Item 1</p>","<span>Item 2</span>"]
          };
          $scope.items = obj.items.join('');
        }]);
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.10/angular.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.10/angular-sanitize.min.js"></script>
      
      <div ng-app="App" ng-controller="AppController">
        <div id="container" ng-bind-html="items"></div>
      </div>

      【讨论】:

        猜你喜欢
        • 2012-07-14
        • 2016-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多