javascript - 使用 AngularJS ng-bind-html 从 json 数据获取 img src

标签 javascript html json angularjs

所以我遇到了一个有趣的问题,但我还没有找到答案。

假设我从类似 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');

演示:http://plnkr.co/edit/zVllp9bmsU2DoZwDZnCY?p=info

关于javascript - 使用 AngularJS ng-bind-html 从 json 数据获取 img src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24037549/

相关文章:

javascript - 在没有 jquery 的情况下将文本添加到模糊的 textarea 值

javascript - DataTables 列宽不调整大小

javascript - 更改 div 内容的 jQuery 脚本不能完全正常工作

javascript - 按钮未正确调用函数

javascript - 如何安全地 XSS 编码来自 PHP 的不受信任的数据,通过 AJAX 通过 javascript 注入(inject)到 DOM 中?

javascript - Html 到 Canvas 到 Base64 到 PDF

javascript - 处理 rows + cols (html) with hidden elements in JS

javascript - 即使数组有键,json 对象键也会被添加

javascript - JSON 安全最佳实践?

mysql - 如何使用 common_schema 从 JSON 中提取值?