使用Angularjs更改获取的json数据

change the fetched json data using Angularjs

本文关键字:json 数据 获取 Angularjs 使用      更新时间:2024-04-19

我已经获取了json数据,看起来像这样:

 {
     "id": "154",
     "user_id": "1445674241",
     "title": "Power of one",
     "content": "<p><img style='"display: block; margin-left: auto; margin-right: auto;'" src='"/photo.png'" alt='"Power of one'" width='"455'" height='"567'" /></p>'n<p>&nbsp;</p>'n<p>One is really powerful, you are one, God is one, earth is one. Love the one.<img style='"display: block; margin-left: auto; margin-right: auto;'" src='"/photo.png'" alt='"Power of one'" width='"455'" height='"567'" /></p>",
     "num_views": "0",
     "votes_up": "1",
 }

我想使用angular js更改所有img标记的属性(如append-src、change-height&width)。

我还在控制器中使用ng-bind-html呈现html代码。其功能是:

 $scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

帮我更改img标记的属性。

我认为你必须直接在data.content字符串上工作
类似这样的东西:

var newWidth = 123;
data.content = data.content.replace(/(img.*?width=")(.*?)(")/g, function(c1, c2, c3) { return c1 + newWidth + c3; });

您可以为此创建某种自定义过滤器,例如,如果我从数据输入中获得youtube链接,并且我想在嵌入页面之前对其进行修改-

myApp.filter('trustedURL', ['$sce', function($sce){
    return function(input) {
        return $sce.trustAsResourceUrl(input);
    };
}]);
myApp.filter('youtubeEmb', ['$sce', function($sce){
    return function(input) {
        var shortYou = input.match(/youtu.be/g);
        if(shortYou){
            return input.substring(0,input.indexOf('?')).replace(shortYou,"youtube.com/embed");
        }else{
            return input.substring(0,input.indexOf('&')).replace("watch?v=","embed/");
        }
    };
}]);

我的HTML-

<iframe src="data.uri | trustedURL | youtubeEmb"></iframe>

这里是url,类似地,您可以为img标记属性创建一些函数。