0

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?

2
  • 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". Commented Aug 4, 2016 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. Commented Aug 4, 2016 at 14:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.