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

时间:2014-12-18 20:50:11

标签: javascript angularjs node.js express pug

我有一个控制器,通过使用$ 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}}

现在,在google上我发现由于安全问题,jade不允许直接使用html,所以建议使用类似的东西 -

p!= {{post.message}}

p.
   #{post.message}

但是我得到了jade错误,说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调试器中没有显示错误,并在inspect元素中显示 -

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

我可能会出错的任何建议?

1 个答案:

答案 0 :(得分:0)

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

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

您的模板应如下所示:

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

你的obj.message应该包含&lt;和&gt;标签而不是转义序列。

你可以在这里阅读有关$ sce以及如何将角度绑定到html https://docs.angularjs.org/api/ng/service/ $ sce