1

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.

3 Answers 3

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation!
1

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

1 Comment

Thank you, this is the simplest way to do it!
0

You can just assign the function in the controller:

$scope.stringify = JSON.stringify;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.