Ciri
Ciri

Reputation: 371

JSON stringify with AngularJS on the fly transformation

Why can I not use something like this?

<input type="text" ng-model="testVal">
<pre>{{JSON.stringify(testVal,null,4)}}</pre>

If I remove the JSON.stringify() method my code works just fine.

Upvotes: 1

Views: 1283

Answers (3)

davidkonrad
davidkonrad

Reputation: 85528

You can simply use | json :

{{ testVal | json }}

or add JSON to $scope :

$scope.JSON = JSON 

then

<pre>{{ JSON.stringify(testVal) }}</pre>

works

http://plnkr.co/edit/PPXK36BbTslkK5FjfP4x?p=preview

Upvotes: 1

s.alem
s.alem

Reputation: 13079

You can just assign the function in the controller:

$scope.stringify = JSON.stringify;

Upvotes: 0

Harry B
Harry B

Reputation: 2972

The double brackets syntax {{something}} tells angular to look in the $scope object for a match.

So {{name}} matches to $scope.name set in your controller.

You can use methods in here (and I would recommend it to keep your view files clean) and this will resolve your problem.

So in the controller:

$scope.stringify = function(value, replacer, space)
{
    return JSON.stringify(value,replacer,space);
}

... then in your view:

<pre>{{stringify(testVal,null,4)}}</pre>

Upvotes: 3

Related Questions