Dynamic ng-controller with Angular

Dynamic ng-controller with Angular

If you’re dynamically pulling in views through frameworks like jQuery, or anything else that isn’t Angular, Angular won’t know you are referencing the controller on the page without re-compiling.  To let Angular know about your new HTML is pretty straight forward.  I have a method in my Main controller that I can access whenever I need to.

    $scope.activateView = function (elements) {
        $compile(elements.contents())($scope);
        $scope.$apply();
    };

I then have a common function I setup to be able to access anywhere I need in the application.

    function activateAngularController(controllerWrapperId) {
        var wrapperElement = angular.element(document.getElementById(controllerWrapperId));
        var mController = angular.element(document.getElementById("body"));
        mController.scope().activateView(wrapperElement);
    }

My Main controller is defined in the body tag, hence it’s getting it from body to populate the mController variable.

<body ng-app="coolApp" ng-controller="MainController">

And finally when you’re instantiating your HTML dynamically, just have it wrapped in a div you can reference.

<div id="myControllerWrapper">
 <div ng-controller="MyController as my">
     <!-- Your html and angular stuff -->
 </div>
</div>

<script>
activateAngularController('myControllerWrapper');
</script>

And that should do it. Angular now knows about the new HTML and directives within your controller wrapper. Alright Peter man, ouu ouu!

Comments are closed.