Using AngularJS with innerHTML

user2494584 picture user2494584 · Jul 15, 2013 · Viewed 29.3k times · Source

I have some AngularJS stuff that holds a bunch of arrays and data. Once a user uploads a file, the file gets parsed up and saved into the scope with its different arrays. However, after all of this and the file is held in the scope, I try to update the innerHTML, but the AngularJS code does not work. I use ng-repeat to create a table based on the arrays, but it remains a single cell with content looking like {{column}} and the like.

I have had extreme difficulty using directives and templates because my index.html says that app and module, etc, are undefined when I do something such as app.directive(...

The significant parts of my index.html file include:

<html ng-app>
... //once a file is uploaded, total.js is called;
//this was so the app didn't try to run before a file was uploaded
<div id="someStuff">This will become a table once a file is uploaded</div>

This is a simple example of how my scope is set up in total.js:

function sheet($rootScope, $parse){
    $rootScope.stuff = text; 
//text is a variable that contains the file's contents as a string
};

document.getElementById('someStuff').innerHTML="<div ng-controller='sheet'>{{stuff}}</div>";

The HTML changes but instead of printing the file's contents, it only prints {{stuff}}. How can I get the innerHTML to understand that it contains AngularJS, preferably without using a partial or a directive, unless you can thoroughly explain where I'd input it and the syntax of it.

Edit 1: I have tried using $compile but it is marked as undefined. I looked at this to figure out the compile problem, but I don't understand rtcherry's syntax, and how I should apply it to my own code.

Edit 2: I still receive $compile undefined errors when I include it like so:

function sheet($rootScope, $parse, $compile){...};
document.getElementById('someStuff').innerHTML=$compile("<div ng-controller='sheet'>
{{stuff}}</div>")(scope);

Edit 3: While itcouldevenbeaboat's comment was extremely unhelpful, I decided I should perhaps show you the directive way I attempted to do it.

I included this code under my sheet function:

var app = angular.module('App', []);
app.directive('spreadsheeet', function($compile){
    return{
        templateUrl: innerHTML.html
    }
});

Where innerHTML contains <div ng-controller='sheet'>{{stuff}}</div>and on index.html I've included <div spreadsheet></div>

With this, I receive no errors, but the text does not show up, neither as {{stuff}} or as the file's contents. Even when I do something simple, such as provide template: "<h2>Hello!</h2>" instead of a templateUrl, I cannot get Hello! to print.

Answer

Mher picture Mher · Oct 22, 2014

It works for me

document.getElementById('someStuff').innerHTML = "<div ng-controller='sheet'>{{stuff}}</div>";
$compile( document.getElementById('someStuff') )($scope);