Question

I am trying to use ACE Editor to display code (JSON response) on a page. When I try the ace example on the landing page, index.html, it works. But when I use the same code on page2.html it wont work.

HTML

<div id="editor">
  function foo(items) {
   var i;
   for (i = 0; i &lt; items.length; i++) {
     alert("Ace Rocks " + items[i]);
   };
</div>

SCRIPT: the same code works on index.html but wont work when placed on other pages.

var editor = ace.edit("editor");
editor.setTheme("ace/theme/twilight");
editor.getSession().setMode("ace/mode/javascript");

I even tried putting the above js code on an external file <script src-"js/script,js"></script> with hopes it will be available on any page.

Since its an AngularJS App, page2.html and other pages are loaded via ngView

Was it helpful?

Solution

As @Michael suggested, Ace is evaluating var editor = ace.edit("editor") before the content of the page is loaded. Instead of using the script in the html or in an external script I had to put the script code inside the page2.html controller....

function page2Ctrl ($scope, $http) {
 var editor = ace.edit("editor");
 editor.setTheme("ace/theme/twilight");
 editor.getSession().setMode("ace/mode/javascript");
}

When app goes on page2.html the page's ctrl gets initiated.

OTHER TIPS

If you have a function inside script then put the var editor = ace.edit("editor");

editor.setTheme("ace/theme/twilight");
editor.getSession().setMode("ace/mode/javascript");

inside the same function.
You can also do:

   function doOnLoad()
    {
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/twilight");
        editor.getSession().setMode("ace/mode/javascript");
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top