所以我遇到了一个有趣的问题,但我还没有找到答案。
假设我从类似 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...'
在使用 ng-bind-html 将 json 数据绑定(bind)到我页面上的 innerHTML 时,我如何能够从该 IMG 获取 src。 (在 img 本身上使用 display:none; 所以它不会显示)
我尝试了 getElementsByTags 等,但没有返回有效值。
是否有某种“Angular ”的方式来做到这一点或...?
BR
最佳答案
根据存储在对象中的 html,您可以这样做:
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');
}
这是一个演示:http://plnkr.co/edit/JXy97lrN5FyW1MK33qO1?p=preview
此解决方案假定 jQuery 未包含在项目中。
这也有效:
$scope.imgPath = angular.element(json.description).attr('src');
关于javascript - 使用 AngularJS ng-bind-html 从 json 数据获取 img src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24037549/