Search code examples
javascriptangularjsjsonui-codemirror

Display json object in angularjs codemirror


I have a json object and want to display it on codemirror using angularjs codemirror but it got an error saying ui-codemirror cannot use an object or an array as a model. Then I tried to convert the object into string using JSON.stringify, the string does not format nicely in codemirror. Anyone can help me to figure out how to make my code in formatted nicely in codemirror? Thanks

ex:

//inside javascript

    $scope.code = {
        "name": "user1",
        "id": "34",
        "value": [3, 5, 4]
    };
    
     $scope.editorOptions = {
          lineWrapping : true,
          lineNumbers: true,
          mode: 'application/json',
        };

//inside html
<ui-codemirror ui-codemirror-opts="editorOptions" ng-model="code"></ui-codemirror>

It returns an error for this: ui-codemirror cannot use an object or an array as a model

if I change to JSON.stringify($scope.code), code mirror display like this:

{"name":"user1","id":"34","value":[3,5,4]}

However, I want it to display as this:

{

      "name": "user1",
      "id": "34",
      "value": [3, 5, 4]
    }

Any help? Thanks


Solution

  • You can specify the indentation:

    $scope.codeView = JSON.stringify($scope.code, null, 4);
    

    Live example