Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use angular.toJson on a angular controller or scope

Tags:

Please see my following jsFiddle example where I am trying to push an Angular.js object into a JSon representations using angular.toJson. What I get is just "$SCOPE" as the result.

http://jsfiddle.net/K2GsS/12/

What I want to do is get the current properties and values. In this example what I would hope to see is

{ firstName: 'Frank', lastName: 'Williams' } 

Is there a better way to get at that data in JSon form (ie not using scope)? Obviously I could hand roll a method that takes the values and pushes out a JSon representation but as the controller changes so too would that function so I would rather just call a toJson type method. Anyone know of the proper way to do this? Thanks in advance.

like image 942
likestoski Avatar asked Aug 05 '12 19:08

likestoski


People also ask

What is angular toJson?

The angular. toJson() Function in AngularJS is used to serialize the javascript object into a JSON – formatted string. It takes the javascript object and returns a JSON string.

What are controllers used for in angular?

AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions.

Is there scope for angular?

AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.


1 Answers

I can see that you are coming from the jQuery world, but with angular.js things are getting much simpler, please check this jsFiddle: http://jsfiddle.net/pkozlowski_opensource/ASspB/1/

With angular.js you can attach events much, much simpler:

 <input type="button" ng-click="showJson()" value="Object To JSON" /> 

and then in your controller:

 $scope.showJson = function() {     $scope.json = angular.toJson($scope.user); } 

In fact this could be done even easier with angular.js filters, check this jsFiddle: http://jsfiddle.net/pkozlowski_opensource/ASspB/2/ which has:

{{user | json}} 

With angular.js you need to "unlearn" a bit some of the jQuery habits, but this is good since things get much, much easier most of the time.

like image 110
pkozlowski.opensource Avatar answered Oct 16 '22 08:10

pkozlowski.opensource