【问题标题】:AngularJS' $sce.trustAsHtml being ignoredAngularJS 的 $sce.trustAsHtml 被忽略
【发布时间】:2013-12-10 21:28:51
【问题描述】:

我是 AngularJS 的新手,我觉得我只是触及了框架可能实现的表面。但是,我遇到了 sce.trustAsHtml 函数的问题。我正在运行 AngularJS 1.2.4。

在我的应用程序中,我正在使用 JSON 加载项目。这些项目使用指令显示在列表中。有时,我想将 HTML 注入检索到的内容中(例如,使链接可点击)。

我读过我可以使用 $sce.trustAsHtml 来允许绑定 html。但是,以下 sn-p 不起作用。我希望所有项目都替换为粗体文本“测试”,而是为每个项目显示<strong>Test</strong>

有没有一种简单的方法可以让这个 sn-p 工作?

angular.directive('ngStream', function($timeout, $sce) {
    var url = "getitems.json";
    return {
        restrict: 'A',
        scope: {},
        templateUrl: 'templates/app_item.html',
        controller: ['$scope', '$http', function($scope, $http) {
            $scope.getItems = function() {
                $http.get(url,{}).success(function(data, status, headers, config) {
                    $scope.items = data;
                });
            }
        }],
        link: function(scope, iElement, iAttrs, ctrl) {
            scope.getItems();
            scope.$watch('items', function(newVal) { if (newVal) {
                angular.forEach(newVal, function(vars,i) {
                    # Example html string for testing purposes.
                    var editedContent = '<strong>Test</strong>';
                    newVal[i].contentHtml = $sce.trustAsHtml(editedContent)
                });
            }});
        },
    }
});

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    你的模板上有什么? $sce.trustAsHtml 必须与ng-bind-html 一起使用,而不是普通的ng-bind(或{{}}

    【讨论】:

    • 谢谢!我的模板曾经是:{{ item.contentHtml }}。通过将其更改为 &lt;span ng-bind-html="item.contentHtml"&gt;&lt;/span&gt; 它工作。你知道使用 ng-bind-html 的更简洁的方法(不使用不必要的 span 标签)吗?
    • AFAIK 这是使用ng-bind-html的唯一方法。
    • 你通过强调必须与ng-bind-html一起使用来拯救我的一天
    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 2014-08-18
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 2016-06-05
    • 2014-02-25
    相关资源
    最近更新 更多