I'm trying to solve this issue: I have an array of objects, each containing an image
property, which is an absolute url to a remote image.
I have to find the first object with an image larger than 500px, extract it from the array and putting it into another object.
What I've tried to do is to cycle through the array and call a function that loads the image and returns the width, but it doesn't work…
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, loadImages) {
var articles = [
{
"image": "http://i.res.24o.it/images2010/logo.gif"
},
{
"image": "http://www.avvenire.it/Commenti/PublishingImages/ImmaginiArticolo/Originali/gispponema_47548148.jpg"
},
{
"image": "http://i.dailymail.co.uk/i/pix/2012/03/07/article-2111440-1211004C000005DC-146_1024x615_large.jpg"
},
{
"image": "http://www.brookings.edu/~/media/research/images/w/wa%20we/wealthy002/wealthy002_16x9.jpg"
},
{
"image": "http://www.avvenire.it/Mondo/PublishingImages/ImmaginiArticolo/Originali/oREUVENRIV_47517580.jpg"
}
];
$scope.articles = loadImages.getCover(articles);
})
.factory('loadImages', function(){
function getMeta(url){
var img = new Image();
img.src = url;
img.onload = function(){
return img.width;
};
}
return {
getCover: function(articles) {
var cover = null;
for (var i = 0; i < articles.length; i++) {
if(articles[i].image){
var w = getMeta(articles[i].image);
if(w > 500){
cover = articles[i];
articles.splice(i,0);
}
}
}
return {
cover: cover,
articles: articles
};
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>{{articles}}!</p>
</body>
</html>
plunkr: http://plnkr.co/edit/tCacRy0jf9WhWreWIK7I
Do you have any suggestion? What am I doing wrong? Thanks