正在剥离$ templateCache中的AngularJS动态部分

时间:2015-08-21 15:37:42

标签: javascript json angularjs

要么我的代码闹鬼,要么我犯了错误:

我有一个json feed:

{
  "sections": [
    {
      "identifier": "header",
      "blocks": [
        {
          "identifier": "onebyone",
          "html": "<h1>API</h1>"
        },
        {
          "identifier": "onebyone",
          "html": "<h1>API</h1>"
        }
      ]
    },
    {
      "identifier": "content",
      "blocks": []
    },
    {
      "identifier": "footer",
      "blocks": []
    }
  ]
}

我在AngularJS控制器中进行调用,然后对各个部分进行排序并尝试连接html块,所以:

cmsApp.controller('cmsPageCtrl', function($scope, $http, $templateCache, $sce) {

    $http.get("/api.php/api/page/home")
        .success(
            function(response) {
                $scope.sections = [];

                response.sections.forEach(function(el, idx, arr) {
                    var id = el.identifier;

                    $scope.sections[id] = el;
                    //$scope.sections[id].template = "<h1>HOI</h1>";
                    $scope.sections[id].template = 'header.html';

                    var template = "TEST";

                    el.blocks.forEach(function(el, idx, arr) {

                        var partial = el.html;
                        template = template + partial;
                    });

                    template = template + "<div><b>b</b>TEST1</div>";
                    console.log(id);
                    console.log(template);

                    $scope.sections[id].template = 'header.html';

                    $templateCache.put('header.html', $sce.trustAsHtml(template));
                    console.log(template);

                });
            }
        );
});

现在可以预期以下输出:

<body ng-app="cmsApp" ng-controller="cmsPageCtrl">
    <ng-include src="sections.header.template"></ng-include>
</body>

要成为: TEST<h1>API</h1><h1>API</h1><div><b>b</b>TEST1</div>

结果是: <span class="ng-scope">TEST</span><div class="ng-scope"><b>b</b>TEST1</div>

控制台输出是:

cms.ctrl.js (line 33)    TEST<h1>API</h1><h1>API</h1><div><b>b</b>TEST1</div>
cms.ctrl.js (line 34)    TEST<h1>API</h1><h1>API</h1><div><b>b</b>TEST1</div>
cms.ctrl.js (line 39)    content
cms.ctrl.js (line 33)    TEST<div><b>b</b>TEST1</div>
cms.ctrl.js (line 34)    TEST<div><b>b</b>TEST1</div>
cms.ctrl.js (line 39)    footer
cms.ctrl.js (line 33)    TEST<div><b>b</b>TEST1</div>
cms.ctrl.js (line 34)    TEST<div><b>b</b>TEST1</div>
cms.ctrl.js (line 39)

负责在标题部分输出中剥离HTML?

1 个答案:

答案 0 :(得分:1)

Angular默认情况下会防止注入。如果你真的想这样做,你需要包含ng-sanitize插件,然后将模块添加到你的app:

angular.module('myApp', ['ngSanitize']);

然后使用ng-bind-html指令绑定您的html内容。

ng-bind-html="myHTML"

Documentation

相关问题