Search code examples
javascriptjqueryangularjscodemirror

Code Beautification with angular-ui-codemirror with indention


I generated xml code with jquery by using following code,

var _outerBlock = $("<outerBlock>");
for (var i = 0; i < 10; i++) {
  var _innerBlock = $("<innerBlock>Serial " + i + "</innerBlock>")
  _outerBlock.append(_innerBlock)
}
var _tmp = $("<div>");
var $output = _tmp.html();

Now I am getting one line xml code in $output variable. I tried using codemirror.js to beautify this code, its applying styling but it is not adding indention.

Here What I tried from browser console with plain codemirror.js

var myCodeMirror = CodeMirror(document.body, {
  value: code,
  mode:  "text/html",
  lineNumbers:true
});

How Can I use indention? How can I display code with angular-ui-codemirror?


Solution

  • For correct xml syntax indentation you need to include

    <script type="text/javascript" src="codemirror/mode/xml/xml.js"></script>
    

    (path to xml mode js file may be different, but you anyways need such defined..)

    Then you use it like:

    config = {
        mode : "xml",
        htmlMode: true,
        // ...
    };
    

    ..and in angular you append ui-codemirror to what ever element you need.

    In angular, setup is given though differently:

    myAppModule.controller('MyController', [ '$scope', function($scope) {
    $scope.editorOptions = {
        lineWrapping : true,
        lineNumbers: true,
        readOnly: 'nocursor',
        mode: 'xml',
    };
    

    }]);

    .. And

    <ui-codemirror ui-codemirror-opts="editorOptions"></ui-codemirror>
    

    Sources / further reading:

    https://libraries.io/bower/angular-sdco-tools

    CodeMirror HTML mode not working

    https://github.com/angular-ui/ui-codemirror/blob/master/README.md