{foo|json}
可以很好地输出$ scope的子集。如何将整个范围发送到json
过滤器?
答案 0 :(得分:0)
事实证明,JSON过滤器不允许您输出整个$scope
对象,即使您尝试使用controllerAs
语法欺骗它并将注入的$scope
附加到你的背景。
模板:
<div ng-app="app">
<div ng-controller="TestCtrl as vm">
<div ng-bind="vm.foo | json"></div>
<div ng-bind="vm.scope | json"></div>
</div>
</div>
JS:
var app = angular.module('app', [])
.controller('TestCtrl', function ($scope) {
var vm = this;
vm.foo = {
bar: "test bar",
foobar: "test foobar"
};
vm.scope = $scope;
console.log(vm.scope);
});
在此示例中Fiddle,
{ "bar": "test bar", "foobar": "test foobar" }
输出vm.foo
但
"$SCOPE"
输出vm.scope
。
因此,您似乎无法将实际范围对象发送到json过滤器。您需要循环并创建一个只包含您需要的相关数据的新对象。在这种情况下你不能使用angular.copy
,因为angular会禁止它。
答案 1 :(得分:0)
Angular拥有它自己的toJSON函数,这会阻止你正常使用它。
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
function toJsonReplacer(key, value) {
....
} else if (isScope(value)) {
val = '$SCOPE';
}
....
}
除非你喜欢这样,否则可能是一种黑客攻击,因为这个角度模板中的= $ $范围。
<div ng-repeat="(k, v) in ($$=this)">
<div ng-if="k!='$$' && k!='this'">key: {{k}}
<pre ng-bind="$$[k]|json:4"></pre>
</div>
</div>
完整代码段或fiddle
var app = angular.module('app', [])
.controller('TestCtrl', function ($scope) {
$scope.foo = {
bar: "test bar",
foobar: "test foobar"
};
$scope.zzz = {
bar: "test bar",
foobar: "test foobar"
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="TestCtrl">
<div ng-repeat="(k, v) in ($$=this)">
<div ng-if="k!='$$' && k!='this'">key: {{k}}
<pre ng-bind="$$[k]|json:4"></pre>
</div>
</div>
</div>
</div>
&#13;
或者如果你想将$ scope作为单个对象JSON,你可以这样做或fiddle
<div ng-init="$scope={}">
<div ng-repeat="(k, v) in ($$=this)" ng-init="$scope[k] = $$[k]" ng-if="k!=='$$'&&k!=='this'&&k!=='$scope'">
</div>
</div>
<pre ng-bind="$scope|json:4"></pre>
输出
{
"foo": {
"bar": "test bar",
"foobar": "test foobar"
},
"zzz": {
"bar": "test bar",
"foobar": "test foobar"
}
}