Angular.js如何从json文件呈现HTML标签 [英] Angular.js How to render a HTML tag from json file
问题描述
我正在尝试解析角度页面中的html值,不确定我在做什么错,我在控制台中收到此错误:
I am trying to parse html value in my angular page, not sure what I am doing wrong, I am getting this error in my console:
app.js:13 Uncaught SyntaxError:Unexpected token)
app.js:13 Uncaught SyntaxError: Unexpected token )
app.js
var App = angular.module('App', []);
App.controller('ProjectCtrl', function($scope, $http) {
$http.get('app/test.json')
.then(function(res){
$scope.projects = res.data;
});
App.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
});
test.json
[
{ "icon": "<i class="fa fa-github fa-3x" aria-hidden="true"></i>", "name": "lovelycss" },
{ "icon": "<i class="fa fa-github fa-3x" aria-hidden="true"></i>", "name": "lovely-icons" }
]
html:
<div ng-controller="ProjectCtrl">
<ul>
<li ng-repeat="project in projects">
<div ng-bind-html="'{{project.icon}}' | to_trusted"></div>- <em>{{project.name}}</em>
</li>
</ul>
</div>
我要存档的内容是: http://jsfiddle.net/JfGVE/1547/
我想要一个json来加载图标和文本.
I want a json loading the icons and the text.
我希望现在一切都会清楚.
I hope now this will be clear.
推荐答案
在控制器声明中缺少}
,在过滤器声明中缺少[
:
You are missing a }
in your controller declaration and a [
in your filter declaration:
var App = angular.module('App', []);
App.controller('ProjectCtrl', function($scope, $http) {
$http.get('app/test.json')
.then(function(res){
$scope.projects = res.data;
});
}); // You are missing a '}' here
App.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]); // You are missing a ']' here
您还必须编辑JSON以转义引号"
You will also have to edit your JSON to escape your quotes "
[
{
"icon": "<i class=\"fa fa-github fa-3x\" aria-hidden=\"true\"></i>",
"name": "lovelycss"
}, {
"icon": "<i class=\"fa fa-github fa-3x\" aria-hidden=\"true\"></i>",
"name": "lovely-icons"
}
]
并且您传递给ng-bind-html
的表达式也是错误的.由于单引号'
,您正在将文字字符串'{{project.icon}}'
传递给过滤器.您必须删除引号和花括号,因为ng-bind-html
指令需要使用表达式作为参数.
And the expression you are passing to ng-bind-html
is also wrong. Because of the single quotes '
you are passing a literal string '{{project.icon}}'
to the filter. You have to remove the quotes and the curly braces, because the ng-bind-html
directive needs an expression as a parameter.
<div ng-controller="ProjectCtrl">
<ul>
<li ng-repeat="project in projects">
<div ng-bind-html="project.icon | to_trusted"></div>- <em>{{project.name}}</em>
</li>
</ul>
</div>
这篇关于Angular.js如何从json文件呈现HTML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!