将包含 html 的动态变量从 angularjs 加载到 jade 模板



我有一个控制器,它通过使用$http获取一些数据,然后将其存储在数组$scope.feeds中。现在我的玉句法是——

div(ng-repeat="post in feeds")
        div.box.box-success
            div.box-header
                h3.box-title
                    i.fa.fa-user
                    | {{post.firstName}} {{post.lastName}}
                div.pull-right
                    i.fa.fa-clock-o
                    //| {{(new Date(post.date)).toTimeString().split(":")[0]}} {{(new Date(post.date)).toTimeString().split(":")[1]}}, {{(new Date(post.date)).toDateString()}}
            div.box-body
                p.
                   {{post.message}}

现在,在谷歌上,我发现出于安全考虑,jade不允许在这里直接html,因此建议使用类似的东西 -

p!= {{post.message}}

p.
   #{post.message}

但是我收到玉错误,说帖子消息未定义。 附言我能够通过显示 {{post.message}} 看到类似 - ass<b>sada</b> 的字符串,因此 post.message 不是未定义的。所以,谁能告诉我如何将 html 内容添加到这个段落标签。请注意,我的控制器代码示例是这样的 -

angular.module('student').controller('StudentDashBoardController', function($rootScope, $scope,$http,$location,mvNotifier) {
    $scope.feeds = [];
    var obj = { "message" : "asdsd&lt;b&gt;asd&lt;/b&gt;","firstName":"test","lastName":"test" ,"username" : "test@test.com", "dislikes" : [ ], "likes" : [ ], "tags" : [ ], "comments" : [ ], "views" : 1, "date" : "2014-12-18T19:08:44Z", "__v" : 0 };
    $scope.feeds.push(obj);
});

我还尝试在控制器代码中添加它 -

$scope.decode = function(textData){
        var textarea=document.createElement("textarea");
        textarea.innerHTML = textData;
        return textarea.textContent;
    };
$scope.to_trusted = function(html_code) {
        return $sce.trustAsHtml(html_code);
    }

而玉石部分更新为——

p(ng-bind-html="{{to_trusted(decode(post.message))}}")

在 Chrome 调试器中没有显示错误,并在检查元素中显示此错误 -

<p ng-bind-html="asdsd<b>asd</b>"></p>

任何建议我可能出错的地方??

你很困惑。首先,玉模板在服务器上编译,角度模板在客户端编译。因此,当然post.message不是在服务器上定义的,因为您在客户端代码中定义它。

其次,你可能指的是角度不允许html,而不是jade。对于大多数 html 来说都是如此,但它确实允许您绑定有限数量的标签而不"信任"html。你只需要使用ngBindHtml。

您的模板应如下所示:

p(ng-bind-html="post.message")

您的obj.message应该包含<和>标签,而不是转义序列。

您可以在此处阅读有关$sce以及如何将角度绑定到html的信息 https://docs.angularjs.org/api/ng/service/$sce

最新更新