AngularJS: textarea bind to JSON object shows "object-object"

how to display json data in textarea
angular 4 textarea binding
angular object to json
angular json stringify
angular json formatter
angular pretty print json
react-json textarea
angular 6 textarea ((ngmodel))

I am fairly new to AngularJS.

I am trying to bind an object to a textarea.

HTML:

<textarea rows="5" cols="10" ng-model="menuItem.preset"></textarea>

Model:

{
    "kind": "title",
    "label": "ADD_TITLE",
    "iconSrc": "textTitle.png",
    "experimentInclude": "",
    "experimentExclude": "three",
    "preset": {
        "compType": "richTitle",
        "styleId": "txtNew"
    }
}

Result:

How can I show the JSON stringified (and later save it as an object again)?


You need a custom directive that parses the input to an object, and displays the object as a string, respectively:

Something like:

angular.module('yourApp').directive('jsonText', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {            
          function into(input) {
            return JSON.parse(input);
          }
          function out(data) {
            return JSON.stringify(data);
          }
          ngModel.$parsers.push(into);
          ngModel.$formatters.push(out);

        }
    };
});
<textarea json-text rows="5" cols="10" ng-model="menuItem.preset"></textarea>

Fiddle: http://jsfiddle.net/HzYQn/

ngModel, fromJson · angular.identity · angular.injector · angular. The ngModel directive binds an input , select , textarea (or custom form This is important to know when binding inputs to models that are objects (e.g. Date ) or collections (e.g. arrays). The following example shows a simple way to utilize CSS transitions to style an  AngularJS: textarea bind to JSON object shows “object-object” Posted by: admin November 12, 2017 Leave a comment. Questions: I am fairly new to AngularJS.


I’ve just researched what I believe to be the most "proper" way of doing this, as I needed it for my https://github.com/vorburger/MUI.js... So here is a Plonker with my solution. It’s based on & is essentially a special case (i.e. an application of) the related Q How to do two-way filtering in angular.js? The added twist is that model updates should also change the textbox.. that's what the $watch / $setViewValue / $render thing does.

var app = angular.module('app', []);

app.directive('jsonText', function() {
  return {
    restrict: 'A', // only activate on element attribute
    require: 'ngModel', // get a hold of NgModelController
    link: function(scope, element, attrs, ngModelCtrl) {

      var lastValid;

      // push() if faster than unshift(), and avail. in IE8 and earlier (unshift isn't)
      ngModelCtrl.$parsers.push(fromUser);
      ngModelCtrl.$formatters.push(toUser);

      // clear any invalid changes on blur
      element.bind('blur', function() {
        element.val(toUser(scope.$eval(attrs.ngModel)));
      });

      // $watch(attrs.ngModel) wouldn't work if this directive created a new scope;
      // see https://stackoverflow.com/questions/14693052/watch-ngmodel-from-inside-directive-using-isolate-scope how to do it then
      scope.$watch(attrs.ngModel, function(newValue, oldValue) {
        lastValid = lastValid || newValue;

        if (newValue != oldValue) {
          ngModelCtrl.$setViewValue(toUser(newValue));

          // TODO avoid this causing the focus of the input to be lost..
          ngModelCtrl.$render();
        }
      }, true); // MUST use objectEquality (true) here, for some reason..

      function fromUser(text) {
        // Beware: trim() is not available in old browsers
        if (!text || text.trim() === '') {
          return {};
        } else {
          try {
            lastValid = angular.fromJson(text);
            ngModelCtrl.$setValidity('invalidJson', true);
          } catch (e) {
            ngModelCtrl.$setValidity('invalidJson', false);
          }
          return lastValid;
        }
      }

      function toUser(object) {
        // better than JSON.stringify(), because it formats + filters $$hashKey etc.
        return angular.toJson(object, true);
      }
    }
  };
});


app.controller('Ctrl', ['$scope',
  function($scope) {
    $scope.model = {};
    $scope.model.data = {
      "kind": "title",
      "label": "ADD_TITLE",
      "iconSrc": "textTitle.png",
      "experimentInclude": "",
      "experimentExclude": "three",
      "preset": {
        "compType": "richTitle",
        "styleId": "txtNew"
      }
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div ng-app="app" class="container">
  <div ng-controller="Ctrl" class="row">
    <textarea json-text ng-model='model.data' rows="15"></textarea>
    <p>{{ model.data }}</p>
  </div>
</div>

textarea, HTML textarea element control with AngularJS data-binding. The data-binding and If the expression evaluates to a RegExp object, then this is used directly. But i need to convert this string to json object so i can use on my angular js code. so i search on google and i found fromjson() of angular function and i make it done. You can also see how to can use angular.fromjson() for converting string to object.


try with json filter

<textarea rows="5" cols="10" >
   {{ menuItem.preset | json }}
</textarea>

ngModelOptions, This expression should evaluate to an object, whose properties contain the settings. For example: The following example shows how to bind to getter/ setters:. AngularJS is what HTML would have been, had it been designed for building web-apps. Declarative templates with data-binding, MVC, dependency injection and great testability story all implemented with pure client-side JavaScript!


Here is our JSON directive with validity checks:

app.directive('jsonInput', function () {
  'use strict';
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, elem, attr, ctrl) {
        ctrl.$parsers.unshift(function(input) {
          try {
            var obj = JSON.parse(input);
            ctrl.$setValidity('jsonInput', true);
            return obj;
          } catch (e) {
            ctrl.$setValidity('jsonInput', false);
            return null;
          }
        });
        ctrl.$formatters.unshift(function(data) {
          if (data == null) {
            ctrl.$setValidity('jsonInput', false);
            return "";
          }
          try {
            var str = JSON.stringify(data);
            ctrl.$setValidity('jsonInput', true);
            return str;
          } catch (e) {
          ctrl.$setValidity('codeme', false);
              return "";
          }
        });
    }
  };

});

When the user enters invalid JSON, the model is null. When the model contains circular references or is null, the user will see an empty string ("") and the input is invalid.

Enjoy.

ngBind, Enter a name in the Live Preview text box; the greeting below the text box changes instantly. Edit in Plunker. index.html protractor.js. <script> angular. Introduction. AngularJS is a MV* JavaScript framework developed by Google. It is widely use across the industry.In this article, we will read a JSON file and display the information about the same using AngularJS Expression.


also you can define toString method on your model:

  $scope.menuItem.preset.toString = function(){
        return JSON.stringify(this);
    }

http://jsfiddle.net/ceJ4w/19/

and then to synchronise back use watch

http://jsfiddle.net/ceJ4w/20/

but it looks more like dirty hack than solution

ngOptions, Complex Models (objects or collections). By default, ngModel watches the model by reference, not value. This is important to know when binding the select to a  Tag: json,angularjs I have to display name and ownername in html page, data is in JSON format (from MongoDB database) While displaying in html, I am getting name correctly but ownername is not displaying properly instead it's displaying the complete object inside owner.


Angular 6 - value in textarea showing as Object Object, Angular 6 - value in textarea showing as Object Object - json. How to bind json object with variable in typescript Angular2? I have one json file and i want to  Use JSON Forms in AngularJS The created data schema and UI schema are interpreted during runtime, which is when when the web page that contains the form is displayed on the browser, and translated into an AngularJS based UI, which is already fully functional including data binding, validation, etc.


Angular ng-model Directive, Learn JavaScript Learn jQuery Learn React Learn AngularJS Learn JSON The binding goes both ways. If the user changes the value inside the input field, the AngularJS property will also change its value: In the example above, the span will be displayed only if the expression in the ng-show attribute returns true . You can easily bind a JSON array or data to an HTML table in AngularJS. The example that I am going to share with you here is an extension of my previous article on how to sort date extracted from a JSON array and show the data in descending order using AngularJS ng-repeat orderBy filter.


Directive to show JSON in textarea instead of "object-object", When we bind ng-model in textarea to show whole JSON, we land with a documentation : https://docs.angularjs.org/api/ng/type/ngModel. AngularJs access complex nested JSON object: Here in this article we learn how to display all the nested JSON data using nested ng-repeat directive into our HTML table on a button click .i.e how to bind an array of objects using ng-repeat in Angularjs with an example.