AngularJS提取物<img>来自JSON
AngularJS extract <img> from JSON
在AngularJS中解析JSON时,如何提取某些标记,例如img?我有一个JSON文件,其中包含以下数据:
jsonFeed({
"title": "My Blog",
"items": [
{
"title": "Title1",
"description": "<p><a href='"#">Paul<'/a> posted a photo:<'/p><img src='"https://farm8.staticflickr.com/7365/26872407641_cfbb210ee7_m.jpg'"/>"
},
{
"title": "Title2",
"description": "<p><a href='"#">Beth<'/a> posted a photo:<'/p><img src='"https://farm8.staticflickr.com/7287/26333398074_cfbce73532_m.jpg'"/>"
}
]
});
我需要得到每一个帖子的描述中的图像:
<article ng-repeat="post in posts">
<h1>{{ post.title }}</h1>
<img src=""/>
</article>
有没有办法在angularjs中做到这一点,或者使用jQuery更好?
您可以使用regex
:((?:http|https)(?::''/{2}[''w]+)(?:[''/|''.]?)(?:[^''s"]*))
您可以使用$sce来绑定HTML:https://docs.angularjs.org/api/ngSanitize/service/$消毒
var app = angular.module("app", []);
app.controller("MainCtrl", ["$scope", "$sce",
function($scope, $sce) {
$scope.jsonStr = {
"title": "My Blog",
"items": [{
"title": "Title1",
"description": "<p><a href='"#'">Paul<'/a> posted a photo:<'/p><img src='"https://farm8.staticflickr.com/7365/26872407641_cfbb210ee7_m.jpg'"/>"
}, {
"title": "Title2",
"description": "<p><a href='"#'">Beth<'/a> posted a photo:<'/p><img src='"https://farm8.staticflickr.com/7287/26333398074_cfbce73532_m.jpg'"/>"
}]
}
$scope.trustHtml = function(desc) {
return $sce.trustAsHtml(desc);
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
<h1>{{jsonStr.title}}</h1>
<div ng-repeat="post in jsonStr.items">
<h3>{{post.title}}</h3>
<div ng-bind-html="trustHtml(post.description)" />
</div>
</div>
使用jqLite,在链接函数中使用angular.element(post.description)[0].querySelector('img');
(如果您使用的是指令),或者在任何angular.element可用的地方。
您可以使用$limitTo过滤负值来获取标记,然后使用$sance将其渲染为html。
阅读以下文档:https://docs.angularjs.org/api/ng/filter/limitTo
https://docs.angularjs.org/api/ngSanitize/service/$消毒
AngularJS附带jqLite,用angular.element()
调用
obj['items'].forEach(function(val, i){
var elm = angular.element(val['description'])[1].src;
console.log(elm);
});
我该怎么做:
- 在每个项目上循环
- 使用正则表达式获取img url(例如
'<img src='''"(.+)'''"
) - 将图像url(在本例中为
imgUrl
)添加到每个项目
然后在你的html中这样使用:
<article ng-repeat="post in posts">
<h1>{{ post.title }}</h1>
<img ng-src="{{ post.imgUrl }}"/>
</article>
票据
- 我用的是ng src,而不是src
- 正则表达式只是一个快速示例
相关文章:
- AngularJS提取物<img>来自JSON
- 来自JSON数组的Google Maps API生成器
- 来自 JSON 字符串的 AngularJS 对象
- 用来自JSON对象的占位符值替换字符串
- HTML中直接来自JSON的角度数据
- 许多来自JSON的hrefs,在切换时单击会显示diffrent id
- 使用来自 JSON 的 jquery 或 angularJS 的选项创建多个选择
- 为什么我的 JSON 代码使用自己的输出(来自 JSON.stringify)返回“语法错误”
- 主干.js:仅添加来自 JSON 集合获取的新模型
- 如何在 AngularJS 中显示来自 JSON 的值
- D3.js来自 JSON 对象的图表
- 显示来自 json 数据的干净列表
- 本地存储的 json 数组正在打印,但来自 json 的值在 cordova 应用程序中给出未定义
- Angularjs 显示来自 json 的日期格式
- 使用javascript和jquery将“下一个”和“上一个”按钮添加到来自JSON的HTML5音频播放器
- 余烬/车把给出[对象对象]而不是来自JSON对象的字符串
- 来自 JSON 的 Dojo 折线图,具有多个系列和公共 x 轴
- Handlebars在Node Express应用程序中渲染来自json数组的额外空对象
- 来自 JSON 的字符串被写入为文本而不是 DOM 元素
- 来自 json 文件的角度 ui 网格