2

I want to two way binding to a text area that will contain json object as text, and I should able to edit the json object in textarea as two way. working demo is here

<div ng-app="app">
  <div ng-controller="GeojsonController">
    <textarea ng-model="geojson"></textarea>
    <p>Geojson is: {{geojson | json}} </p>
  </div>
</div>

angular.module('app', [])
  .controller('GeojsonController', ['$scope', function($scope) {
    $scope.geojson = {
      "type": "FeatureCollection"
    };
  }]);

Text area content is [object Object]

barteloma
  • 6,403
  • 14
  • 79
  • 173
  • what is `| json` doing? – brk Aug 04 '16 at 11:27
  • @user2181397 Converts an object to a json string – Robin-Hoodie Aug 04 '16 at 11:27
  • `$scope.geojson` is already a json object, that is why you get `[object Object]` in your textarea, you are going to have to use `$scope.geojson` as a string and then convert the string to json. – li0n_za Aug 04 '16 at 11:34
  • Possible duplicate [http://stackoverflow.com/questions/17893708/angularjs-textarea-bind-to-json-object-shows-object-object](http://stackoverflow.com/questions/17893708/angularjs-textarea-bind-to-json-object-shows-object-object) – jjwilly16 Aug 04 '16 at 11:38

3 Answers3

2
<textarea ng-model="geojson" ng-change="update()"></textarea>

$scope.geo = {
  "type": "FeatureCollection"
};
$scope.geojson = angular.toJson($scope.geo);

$scope.update = function() {
    $scope.geo = angular.fromJson($scope.geojson);
}

https://jsfiddle.net/f9fnetca/1/

P.S. Add some handling for invalid json.

Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
2

You can implement a custom directive, using $formatters and $parsers

.directive('toJson', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
     ctrl.$formatters.push(JSON.stringify);
    }
  }
});

<textarea ng-model="geojson" to-json></textarea>

Check out the Custom Validation example in the docs to get a better idea.

marton
  • 1,300
  • 8
  • 16
1

You want to use $formatters and $parsers of ng-model to make bijection between the object in your model, and the text displayed in the input.

Hopefully, there is much simpler by working with a controller function. You show text and work on object. The getJson() method make the work

<div ng-app="app">
  <div ng-controller="GeojsonController">
    <textarea ng-model="geojson"></textarea>
    <p>Geojson is: {{getJson(geojson) | json}} </p>
  </div>
</div>

Then :

angular.module('app', [])
  .controller('GeojsonController', ['$scope', function($scope) {
    $scope.geojson = '{"type": "FeatureCollection"}';

    $scope.getJson = function(){
        return JSON.parse($scope.geojson);
    }
  }]);

Here is JSFiddle : https://jsfiddle.net/bbhoey5g/6/

Nicolas Zozol
  • 6,910
  • 3
  • 50
  • 74