gpt4 book ai didi

javascript - 解码 JSON HTML 数据以在 AngularJs 中显示

转载 作者:行者123 更新时间:2023-11-30 15:58:31 25 4
gpt4 key购买 nike

我有 JSON 数据,其中也有一些 HTML 标签。当我试图在浏览器中显示该数据时,它还会按原样打印 HTML 标记,而不会将它们转换为它们应该显示的内容。请参阅下面的代码。

我的 JSON 数据(ibmndata.php 我正在将 PHP 数据转换为 JSON):

[
{
"title": "<span class='data'>Lectures</span>",
"content" : "lectures.jpg"
},
{
"title": "<span class='data'>Case Study Analysis</span>",
"content" : "case-study.jpg"
},
{
"title": "<span class='data'>Industry Analysis Projects</span>",
"content" : "industry-a.jpg"
},{
"title": "<span class='data'>Summer Internship Projects</span>",
"content" : "summer-internship.jpg"
}
]

我的 Angular 数据

模型(我在其他示例中找到了“ngSanitize”包)

var app = angular.module('ibmnApp', ['ngAnimate', 'ngRoute', 'ngSanitize', 'ui.bootstrap']);

Controller

app.controller('ibmnController', ['$scope', '$http', function($scope, $http)
{
$http.get('ibmndata.php').success(function(data)
{
$scope.ibmnlist = data;
});
}]);

HTML部分

<div class="col-md-9" ng-controller="ibmnController">
<div class="col-md-9" ng-repeat="item in ibmnlist">
<p>{{item.title}}</p>
<p ng-bind-html="item">{{item.content}}</p>
</div>
</div>

我在网上发现了类似的问题,但它的解决方案对我不起作用。请告诉我我的代码中可能存在什么问题,或者建议我在 AngularJs 中执行此操作的方法。谢谢。

最佳答案

这是一个工作的 plunker:http://plnkr.co/edit/fZ5LnxMv5Ngnzyv6fsz2?p=preview

你必须添加“不安全”过滤器:

angular.module('myApp').filter('unsafe', function ($sce) {
return function (val) {
if( (typeof val == 'string' || val instanceof String) ) {
return $sce.trustAsHtml(val);
}
};
});

在 View 中:

<div ng-controller="ibmnController">
<div ng-repeat="item in ibmnlist">

<p ng-bind-html="item.title | unsafe "></p>
<p>{{item.content}}</p>
</div>
</div>

奖励:您正在为已弃用的 $http 使用 success,请改用 then :

官方文档:

// Simple GET request example:

$http({

method: 'GET',

url: '/someUrl'

}).then(function successCallback(response) {

// this callback will be called asynchronously

// when the response is available

}, function errorCallback(response) {

// called asynchronously if an error occurs

// or server returns response with an error status.

});

关于javascript - 解码 JSON HTML 数据以在 AngularJs 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38121231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com