Reputation: 1944
I'm new to angular, so bear with me here.... I've a simple, but dirty, json results file I am pulling into my angularjs page. I am trying to get just the img src from the first img that is found in the returned info. Here is a fiddle with it setup:
var app = angular.module('myApp', ['ngSanitize']);
app.controller('MainCtrl', function ($scope) {
$scope.data = "HEREHLKSDJFKLFJSLK:FJKFJ:KLJSL:KDfj<img src=\"http://www.sierraavalanchecenter.org/sites/default/files/forecast/201411/20141113-074138-0.png\"/ >asdfsdjflksdfj;kasdfkjs;dklfs;df";
});
app.filter('extractSrcUrl', function () {
return function (text) {
var output = angular.element(text).attr('src');
return(output);
}
});
If found the filter idea via this post: getting img src from json data while using AngularJS ng-bind-html
If I get rid of all the json data and just leave: http://www.sierraavalanchecenter.org/sites/default/files/forecast/201411/20141113-074138-0.png\"/ > the filter pulls out the src fine.
However, with my messy data, no results. Should I be using regex somewhere in my controller rather than running filter? Is my data that bad?
Upvotes: 0
Views: 561
Reputation: 1768
You could do either of the following.
Modify your selector code to the following:
var output = angular.element('<div>' + text + '</div>').find('img')[0].attr('src')
Which is probably the safest and easiest way. Note that in angular 1.2 and below (I believe they fixed it in 1.3) this has to be as follows:
var output = angular.element(angular.element('<div>' + text + '</div>').find('img')[0]).attr('src')
The other way is to extract purely using regex as follows:
var output = text.match(/src="([^"]*)"/i)[1]
As a side note - return
isn't a function, normally it's just called as return output;
.
Upvotes: 1