2

We have an app that is a hybrid some angular and some vanilla javascript. We are trying to little by little convert it to angular.

The problem we are facing now is that in one part of the app an HTML template gets injected into the DOM from an ajax call. This HTMl contains

ng-controller="MyController"

But angular does not wire this controller, as we put a console.log on the controller and it never came up. So how do we tell angular to look for this controller if it gets injected into the DOM by non angular code.

ecorvo
  • 3,559
  • 4
  • 24
  • 35
  • 1
    How is it injected? I think you'll have to `$compile` it first so that angular knows waddup – devqon Jan 20 '16 at 16:27
  • The problem is that the HTML gets injected into the DOM by non angular code. Plain jQuery ajax. So this HTML just has a div with ng-controller="MyController" – ecorvo Jan 20 '16 at 16:30
  • just $compile html before adding it to DOM – Petr Averyanov Jan 20 '16 at 16:39
  • OK but where do I put the $compile code? Keep in mind that jquery with plain javascript loads the html, so can you provide an example as to where or how to do this? – ecorvo Jan 20 '16 at 16:42

1 Answers1

1

You'll want to use $compile to allow angular to dynamically compile this HTML template. $watch will allow you to compile this template each time the AJAX-returned string changes.

HTML

<html ng-app="app">
  <body>
    <h1>AJAX-provided HTML into Angular-rendered template</h1>
    <div ng-controller="MyController">
      <div dynamic="html"></div>
    </div>
  </body>
</html>

javascript

var app = angular.module('app', []);

app.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});

function MyController($scope) {
  $scope.updateHtml = function(html){
    $scope.html = "";
  }
}

To force the jQuery to update the Angular code, you could try calling the angular object for that DOM element (then accessing the controller for that object):

jQuery

$.ajax(href, {
  success: function(data){
    var element = angular.element($('#myElement'));
    var scope = element.scope();
    scope.$apply(function(){
       scope.updateHtml(data);
     });
  }
});
Community
  • 1
  • 1
zacran
  • 855
  • 6
  • 18
  • My ajax is outside angular. I am trying to do something like this in this link at the bottom part, but it is not working... https://docs.angularjs.org/api/ng/function/angular.injector – ecorvo Jan 20 '16 at 17:13
  • I updated with executing an angular scope function from outside angular. You can also execute controller functions the same way by creating an ng-controller object with `element.controller()`. – zacran Jan 20 '16 at 17:36