3

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

4

3 回答 3

4

这是项目 A的工作 plunker 。

我只移动ItemCtrl了模板的内部ng-include。我认为主要问题是访问外部范围。

模板现在是:

Item A: 
<div ng-bind-html="trustedContent" ng-controller='ItemCtrl'></div>
于 2013-11-09T22:21:22.653 回答
3

修复: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>

我已将ItemCtrl定义移到ng-switchand之外ng-includedirectives将模糊的优先级混合在一起并不总是明智的:ng-include正在创建一个从父范围继承的范围,但controller仍然是独立的范围。

使控制器的范围成为父范围解决了这个问题。

于 2013-11-09T22:24:20.180 回答
2

另一种方式:

索引.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 示例

于 2013-11-09T22:49:45.367 回答