Nikhilesh Yadav
Nikhilesh Yadav

Reputation: 61

change the fetched json data using Angularjs

I've fetched the json data, which look something like this:

 {
     "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",
 }

I want to change the attributes of all img tags(like append src, change height & width) using angular js.

I am also rendering the html code using ng-bind-html in my controller. And the function for that is :

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

Help me out to change the attribute of img tags.

Upvotes: 0

Views: 82

Answers (2)

Himanshu Aggarwal
Himanshu Aggarwal

Reputation: 1102

You can create some kind custom filter for that, for ex- if I'm getting a youtube link from my data input and I want to modify it before embedding in my page-

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/");
        }
    };
}]);

my HTML-

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

Here it was url, similarly you can create some function for img tag attrs.

Upvotes: 0

MarcoS
MarcoS

Reputation: 17721

I think you have to get your hands dirty working directly on data.content string...
Something like this:

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

Upvotes: 0

Related Questions