Getting Img Src From Json Data While Using Angularjs Ng-bind-html
So I got a interesting question to which I haven't found a answer to. Let's say I got a bunch of data coming from a JSON file like, but somehow one of the main fields looks like t
Solution 1:
Based on the html stored in the object you could do this:
var json = {description : '<img src="http://o.aolcdn.com/hss/storage/midas/37c38989a5f26031be3e0ec5ffc5cd2/200012386/got-hbo-go-crash-2014-04-07-01_thumbnail.jpg"/> Viewing of the Game of Thrones season debut came to a crashing halt yesterday thanks to server problems with HBO Go. The cable outfit first reported the problem late yesterday via Twitter, and finally restored full service early this morning. That...'};
$scope.imgPath = '';
$scope.getImage = function() {
el = angular.element(angular.element('<div>' + json.description + '</div>').find('img')[0]);
$scope.imgPath = el.attr('src');
}
Here is a demo: http://plnkr.co/edit/JXy97lrN5FyW1MK33qO1?p=preview
This solution assumes jQuery isn't included in the project.
This also works:
$scope.imgPath = angular.element(json.description).attr('src');
Solution 2:
The angular way of doing this would be to write a filter that does the massaging that you need.
Something like this:
<divng-bind-html="data | extractSrcUrl"></div>
and then
app.filter('extractSrcUrl', function () {
returnfunction (text) {
var output = awesomeRegexExtractionStuff(text); // fill this inreturn output;
}
});
I attempted a jsfiddle but I couldn't quite get the regex right. Here it is anyway.
Edit: I updated my fiddle using @lucuma's way of extracting the url: http://jsfiddle.net/LxK7W/2/
Post a Comment for "Getting Img Src From Json Data While Using Angularjs Ng-bind-html"