如何使用AngularJS从json数据中删除链接标记

How to remove link tags from json data using AngularJS

本文关键字:删除 链接 数据 何使用 AngularJS json      更新时间:2023-09-26

我目前正在从wordpress网站加载JSON数据,如下所示:

"content": "<p>This is text which <a href="#">may have</a> some random links <a href="#">in</a> it.</p>",

控制器

$http.get($scope.postUrl + $stateParams.postID + '?type[]=post')
    .success( function(data){
        $scope.post = data;
    })
    .error( function() {
        $scope.loading = false;
        $scope.errorMessage = "Item could not be found.";
    })
    .then( function() {
        $scope.loading = false;
    });

HTML

<div ng-bind-html="post.content" class="post-content"></div>

我想删除任何可能在原始"内容"中的链接,最好使用过滤器。其他人有没有遇到过类似的情况并提出了解决方案?

我试着用jquery选择器瞄准他们,但没有成功

$(document).ready(function () { $(".post-content a").contents().unwrap(); });

或在控制器级别:

$scope$on('$viewContentLoaded',function(){$(".post content a").contents().unwrap();})

据推测,由于内容未加载的时间问题,这些功能不起作用。

这两次尝试都很接近,但都没有达到您想要的效果。

首先,Angular的元素接口没有unwrap方法。如果您正在使用jQuery,请忽略它,您可能正在使用jQuery。如果不是,则需要在Angular之前将jQuery作为依赖项引入。

其次,您可以在控制器中完成整个操作。片段:

$http.get($scope.postUrl + $stateParams.postID + '?type[]=post')
.success( function(data){
    var postContent = angular.element(data.content); // This wraps the HTML in jQuery
    postContent.find("a").contents().unwrap(); // Remove a tags
    $scope.post = $('<div>').append(postContent).html(); // Cast to HTML String
})