As mentioned in the title, i can't figure out how to render html inside a partial with ng-bind-html.

Here is a plunker to illustrate.

http://plnkr.co/edit/YFfHsahcum7XA8GcH6b2?p=preview

I tried several combinations of ng-bind, ng-bind-html, $sce.trustAsHtml, {{HTMLString}} but none of it worked. Maybe I'm missing something completely different?

Any help is much appreciated! Thank you

有帮助吗?

解决方案

Here is a working plunker for Item A.

I only moved the ItemCtrl inside the template for ng-include. I think the main issue was access to the outside scope.

template is now:

Item A: 
<div ng-bind-html="trustedContent" ng-controller='ItemCtrl'></div>

其他提示

Fix: http://plnkr.co/edit/7qd3INmYAmUfJPluwfem?p=preview

  <div ng-controller='ItemCtrl'>
    <div ng-switch on="item.type">

        <div ng-switch-when="A">
            <div ng-include='"item_A.html"' ></div>
        </div>

        <div ng-switch-when="B">
            <div ng-include='"item_B.html"'></div>
        </div>

    </div>
  </div>

I have moved the ItemCtrl definition outside the ng-switch and ng-include. It is not always wise to mix directives with ambiguous priorities together: ng-include was creating a scope which inherited from the parent scope, but the scope of the controller remained separate.

Making the controller's scope the parent scope solved the problem.

Another way:

index.html:

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <script data-require="angular.js@1.2.0" data-semver="1.2.0" src="http://code.angularjs.org/1.2.0/angular.min.js"></script>
  <script data-require="angular-sanitize@*" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular-sanitize.min.js"></script>
  <style>
    .ac {
      background-color: yellow;
    }
    .bc {
      background-color: orange;
    }
  </style>
  <script>
    var app = angular.module('plunker', ['ngSanitize']);
    app.controller('MainCtrl', function($scope) {
      $scope.items = [{
        "type": "A",
        "url": "item_A.html",
        "content": "<div class=\"ac\">content A</div>"
      }, {
        "type": "B",
        "url": "item_B.html",
        "content": "<div class=\"bc\">content B</div>"
      }]
    });
  </script>
</head>

<body ng-controller="MainCtrl">

  <div ng-repeat="item in items">
    <div ng-switch on="item.type">
      <div ng-switch-when="A">
        <div ng-include="item.url"></div>
      </div>
      <div ng-switch-when="B">
        <div ng-include="item.url"></div>
      </div>
    </div>
  </div>

</body>

</html>

item_A.html:

Item A: 
<div ng-bind-html="item.content"></div>

item_B.html:

Item B: 
<div ng-bind-html="item.content"></div>

Plunker example

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top