Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I loaded a html content from a.html(in other trusted host) file:

<div>
        <div><span ng-bind="propertyA"></span></div>
        <div><span ng-bind="propertyB || 'Test ng-bind.'"></span></div>
        <div><span ng-bind="propertyC"></span></div>             

        <input type="text" value="" ng-model="propertyC" />
</div>

to a variable(loadedHtml) and bind it to my own page and then compiled it:

$scope.htmlContent = $sce.trustAsHtml(loadedHtml);

var elem = angular.element(".need-compile-html > *");                        
$compile(elem)($scope);

it display normally and the directive(ng-bind, ng-model) works correctly.

Now, I want load a controller(a.js) for b.html:

a.js:

(function(angular) {

    angular.module("app").controller("myCtrl", [
        '$scope', function($scope) {

            $scope.propertyA = "Default property."

        }]);

    console.log("myCtrl loaded.");

})(angular);

b.html:

<div ng-controller="myCtrl">
        <div><span ng-bind="propertyA"></span></div>
        <div><span ng-bind="propertyB || 'Test ng-bind.'"></span></div>
        <div><span ng-bind="propertyC"></span></div>             

        <input type="text" value="" ng-model="propertyC" />
 </div>

local js code:

// jscontent is the content of a.js
eval(jscontent);

$scope.htmlContent = $sce.trustAsHtml(loadedHtml);    
var elem = angular.element(".need-compile-html > *");                        
$compile(elem)($scope);

The error occurred: Argument 'myCtrl' is not a function, got undefined. It seems the controller 'myCtrl' is not be registered before $compile(elem)($scope); , but the message 'myCtrl loaded.' outputted in console normally?

What is the correct way to load 'myCtrl' dynamically?

share|improve this question
    
There is an alternative approach using ng-include where you would have the HTML to be included as a separate file, and within that HTML you would define its controller. This appears to me much easier and "controllable". – FDavidov Aug 4 at 12:10
    
Dynamic loading of controllers isn't officially a supported feature of angular, but there are a few 3rd party libraries that make it possible; it is generally referred to as "lazy loading", even though that term is more commonly used with data than code modules. – Claies Aug 4 at 14:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.