<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs@1.5.5" data-semver="1.5.5" src="https://code.angularjs.org/1.5.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="BaseController">
<h1>{{title}}</h1>
<br/><br/>
JSON Data:
<br/><br/>
{{jsonData}}
<br/><br/>
Parsed Data:
<br/><br/>
{{data}}
<br/><br/>
Firstname ::
{{data.person.firstname}}
<br/><br/><br/><br/>
<a href="runTest.html">Run Tests</a>
</body>
</html>
// Code goes here
var app = angular.module("app", []);
app.controller("BaseController", function($scope) {
$scope.title = "Angular.FromJson";
$scope.jsonData = '{"person":{"firstname":"Shashikanth","lastname":"Kota"},"address":{"city":"Omaha","state":"NE"}}';
$scope.data = angular.fromJson($scope.jsonData);
});
/* Styles go here */
Angular.FromJson
It will help in converting json data to angularjs model. Look into the example fore more details.
Syntax:
angular.fromJson(json);
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body ng-app="app" ng-controller="BaseController">
<a href="index.html"><h1>{{title}}</h1></a>
<!-- Add Jasmine -->
<script data-require="jasmine@*" data-semver="2.0.0" src="//cdn.jsdelivr.net/jasmine/2.0.0/jasmine.js"></script>
<!-- Jasmine html & css for reporting -->
<link data-require="jasmine@*" data-semver="2.0.0" rel="stylesheet" href="//cdn.jsdelivr.net/jasmine/2.0.0/jasmine.css" />
<script data-require="jasmine@*" data-semver="2.0.0" src="//cdn.jsdelivr.net/jasmine/2.0.0/jasmine-html.js"></script>
<script data-require="jasmine@*" data-semver="2.0.0" src="//cdn.jsdelivr.net/jasmine/2.0.0/boot.js"></script>
<!-- Add AngularJS -->
<script data-require="angular.js@1.2.25" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
<!-- AngularJS testing helpers -->
<script data-require="angular-mocks@*" data-semver="1.2.16" src="https://code.angularjs.org/1.2.16/angular-mocks.js"></script>
<script src="script.js"></script>
<script src="spec.js"></script>
</body>
</html>
describe('Testing BaseController', function() {
var $scope = null;
var ctrl = null;
//you need to indicate your module in a test
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
ctrl = $controller('BaseController', {
$scope: $scope
});
}));
it('should set title', function() {
expect($scope.title).toEqual('Angular.FromJson');
});
it('should init jsonData', function() {
var jsonData = '{"person":{"firstname":"Shashikanth","lastname":"Kota"},"address":{"city":"Omaha","state":"NE"}}';
expect($scope.jsonData).toEqual(jsonData);
});
it('should convert json to model', function() {
expect($scope.data===$scope.jsonData).toBe(false);
expect($scope.data.person.firstname).toEqual("Shashikanth");
})
});