AngularJS angular.toJson() Function
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.
Syntax:
angular.toJson(object);
Parameter:
- object: It specifies the input will be serialized into the JSON.
Example 1: This example describes the use of the angular.toJson() Function in AngularJS, where <fieldset> tag is utilized to group the related elements in the form, and it creates the box over the elements, in order to serialize the javascript object into a JSON string format.
HTML
<!DOCTYPE html><html><head> <title>AngularJS toJSON() function</title> <script src= </script> <style> body { font-family: "Arial"; text-align: center; line-height: 30px; } h1 { color: green; } </style></head><body> <h1>GeeksforGeeks</h1> <h3>angular.toJson() function</h3> <fieldset> <legend>Company Details</legend> <script> var company = { 'Name': 'GeeksforGeeks', 'Location': 'Noida' } var Industry = { 'Type': 'Software', 'Domain': 'Content & Course' } document.write(angular.toJson(company) +"</br>" + angular.toJson(Industry)); </script> </fieldset></body></html> |
Output:

Example 2: This example describes the use of the angular.toJson() Function in AngularJS, by implementing the button that will display the JSON formatted string data, by serializing the javascript object.
HTML
<!DOCTYPE html><html><head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script> <title>AngularJS toJson() function</title> <style> body { font-family: 'Arial'; text-align: center; } h1 { color: green; } </style></head><body ng-app="app"> <h1>GeeksforGeeks</h1> <h3>angular.toJson() function</h3> <div ng-controller="geek"> <button ng-click="showAlert()"> Click it! </button> </div> <script> var app = angular.module('app', []); app.controller('geek', ['$scope', function($scope) { $scope.showAlert = function() { var string = { Name: 'Quick sort', Type: 'sorting', }; alert(angular.toJson(string)); }; }, ]); </script></body></html> |
Output:






Please Login to comment...