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?
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