ohmmho ohmmho - 2 years ago 140
AngularJS Question

Extracting image from <description> RSS feed with AngularJS

I'm trying to learn AngularJS while building a simple RSS feed. I managed to make a JSON request and retrieve all the data, title, link, description and all of the RSS I parse. I extract the images like this:

angular.forEach(feed.entries, function(value){
value.myImage = $(value.content).find('img').eq(0).attr('src');
console.log('image' + value.myImage);

However, there are some feeds that have different structure and instead placing the images inside
<content> </content>
like this, the image is placed inside
<description> </description>
like this one and I'm trying to get it this way:

angular.forEach(feed.entries, function(value){
value.myImage = $(value.description).find('img').eq(0).attr('src');
console.log('no image' + " " + value.myImage);

But all I get is undefined, so I can not display the image from this feed. I tried different methods but I'm really lost and I'm not sure what I'm doing wrong here.

I've been googling around and trying this for weeks. Any help is super appreciated!

Thanks :)

Here is the JSON object I'm getting.

Object {feedUrl: "https://www.behance.net/rss", title: "Behance Featured Projects", link: "http://www.behance.net", author: "", description: "The latest projects featured on the Behance"…}
$$hashKey: "027"
author: ""
description: "The latest projects featured on the Behance"
entries: Array[10]
0: Object
$$hashKey: "029"
author: ""
categories: Array[0]
content: "<img src="https://mir-s3-cdn-cf.behance.net/projects/404/2e322a33145177.Y3JvcCw4NzYsNjg0LDAsNzc.jpg" style="float:left;margin-right:15px"><br> Various Illustrations by Patryk Hardziej / 2015"
contentSnippet: " Various Illustrations by Patryk Hardziej / 2015"
link: "https://www.behance.net/gallery/33145177/Various-Illustrations-2015"
publishedDate: "Thu, 28 Jan 2016 08:00:02 -0800"
sImage: undefined
title: "Various Illustrations 2015"

Answer Source

Ok, I think I find it :)

The HTML you got from query looks like

<img src="..."> Some text <br/> Some text ...

The find method only works to find child node. In this case, img is not a child of value.content so it return nothing.

You can do

angular.forEach(feed.entries, function(value){
  // force creation of a root node -> find method should works for all cases
  var content = '<div>'+value.content+'</div>';
  value.myImage = $(content).find('img').eq(0).attr('src');
  console.log('image' + value.myImage);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download