Hi Guys,

In this blog I would like to explain how you can create your own directive to shown JSON in a textarea.

Problem
When we bind ng-model in textarea to show whole JSON, we land with a problem that instead of JSON structure it shows object i.e [object, object].

Solution
The solution for this lies in ngModel.NgModelController i.e $formatter method.
Form AngularJS documentation : https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

$formatters: Array of functions to execute, as a pipeline, whenever the model value changes. The functions are called in reverse array order, each passing the value through to the next. The last return value is used as the actual DOM value. Used to format / convert values for display in the control.

Below is implementation example.


index.html
<html ng-app="simpleDirective">
<head>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="Controller">
 {{tempJson}}
 <textarea ng-model="tempJson" json-directive></textarea>
</div>
</body>
</html>
app.js
var app = angular.module('simpleDirective', []);
app.controller("Controller", function($scope){
 $scope.tempJson = {
  "name":"Shankar"
 }
});
app.directive('jsonDirective', function() {
    return {
        restrict: 'A',
  require:"ngModel",
  link: function(scope, element, attr, ngModel){
          function out(data) {
            return JSON.stringify(data);
          }
          ngModel.$formatters.push(out);
        }
    };
});











Good Day :)