0

What's the best approach for a page that has dynamic HTML and Angular? I mean, I'm using DataTables.net for showing search results and I need to be able to edit each cell using Angular. Of course that HTML is not binded in Angular because it was created after a search was performed and Angular has already binded the hmlt to its scope.

Francisco Goldenstein
  • 13,299
  • 7
  • 58
  • 74

1 Answers1

1

It sounds like you are trying to do DOM manipulation with angular. Angular is probably not the best tool for the job if this is the case. Something like the Vanilla.js or jQuery libraries would be better suited.

If you are truly have an involved application within the dynamically loaded HTML the best way would be to mark up the HTML to include your app and manually call angular.bootstrap. Since you manually bootstrap you don't have to worry about nesting apps.

Can I use one ng-app inside another one in AngularJS

http://docs.angularjs.org/api/ng/directive/ngApp

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.

angular.module('HelloApp',[])
.controller('HelloController',[function(){
  var helloController = this;
  helloController.helloWorld = 'Hello World!';
  }]);

setTimeout(function(){
  document.getElementById('insertHere').innerHTML = 
  '<div ng-app="HelloApp" ng-controller="HelloController as helloController">{{helloController.helloWorld}}</div>';
  angular.bootstrap(document, ['HelloApp']);
  
  },5000)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="insertHere">
  Loading in 5 seconds
</div>

If you are trying to utilize an already running app the only way I can think of would be to access/update $rootScope from outside Angular which is bad for reasons explained in the answer.

Community
  • 1
  • 1
  • Your code seems to be what I need but do I have to create an app for each HTML that I add dynamically? – Francisco Goldenstein Feb 01 '16 at 14:46
  • Ideally you would use the [$http](https://docs.angularjs.org/api/ng/service/$http) service and create the dynamic HTML using angular. If you are doing that much DOM manipulation angular is probably not the answer. –  Feb 01 '16 at 14:57
  • I'm showing data in a grid using DataTables.net and that data is editable and it's not a simple text field, it's much more complex and that's why I would like to use Angular's binding mechanism. – Francisco Goldenstein Feb 01 '16 at 15:13
  • Check out [angular-datatables](http://l-lin.github.io/angular-datatables/#/welcome). It appears to be active. –  Feb 01 '16 at 15:29