简体   繁体   中英

angular.forEach with .find

I am searching for a specific field and when found, assign it to a new variable. This works fine as long as the value exist. If it doesn't exist in one record, stops.

angular.forEach($scope.allnews.entries, function (value) {
    value.articleImage = $(value.content).find('img').eq(0).attr('src');
});

$scope.allnews.entries contains a big chunk of json data. The field content contains the img data I am interested about. However, sometimes the content field may not contain any img. As an example,

Record 1: contains img
Record 2: contains img
Record 3: contains img
Record 4: does not contains img
Record 5: does not contains img
Record 6: contains img
Record 7: contains img

My problem is that when I bind articleImage , I will only get the img for record 1, 2 and 3. It will stop retrieving the value for the rest, in this case 6 and 7 won't show anything. Is there a way I can put a condition in this loop so when it doesn't found it adds an empty tag or it doesn't stop? Thanks a lot.

Just test to see if the element exists before trying to get the src attribute from it.

angular.forEach($scope.allnews.entries, function (value) {
    var img = $(value.content).find('img').eq(0);
    value.articleImage = img ? img.attr('src') : null;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM