AngularJS json过滤器
AngularJs中的json过滤器是用来将一个JavaScript对象转换成JSON字符串的。json过滤器将对象或任何表达式与JSON管道化,因此结果将以列表的形式显示,这与表达式的语法绑定。
语法:
{{ object | json : spacing }}
参数值:
- json: 它用于指定对象应以JSON格式显示。
- spacing:这是一个可选的参数,默认值为2,指定每次缩进的空格数。
例子1:这个例子将以JSON格式显示学生的分数。
<!DOCTYPE html>
<html>
<head>
<title>AngularJS json Filter</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body style="text-align: center;">
<div ng-app="result" ng-controller="resultCtrl">
<h1 style="color:green ;">GeeksforGeeks</h1>
<h3>AngularJS json Filter</h3>
<h4>Result:</h4>
<pre>{{marks | json}}</pre>
</div>
<script>
var app = angular.module('result', []);
app.controller('resultCtrl', function (scope) {
scope.marks = {
"Math": 98,
"Computer": 93,
"Physics": 95,
"Chemistry": 95,
"English": 74
};
});
</script>
</body>
</html>
输出:
例子2:这个例子将在JSON中显示水果的名称,每缩进10个空格
<!DOCTYPE html>
<html>
<head>
<title>AngularJS json Filter</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body style="text-align: center;">
<h1 style="color:green ;">GeeksforGeeks</h1>
<h3>AngularJS json Filter</h3>
<div ng-app="fruit" ng-controller="fruitCtrl">
<h4>Fruits:</h4>
<pre>{{fruit | json : 10}}</pre>
</div>
<script>
var app = angular.module('fruit', []);
app.controller('fruitCtrl', function (scope) {
scope.fruit = ["Apple", "Banana", "Mango"];
});
</script>
</body>
</html>
输出: