我编写了一些简单的代码来允许引导模式与角度一起工作,因为它在单击时将链接加载到模式中。现在有问题的链接有自己的角度控制器,这些控制器包含在它们的源代码中。当模态被加载时,我首先使用 jquery 加载它的所有依赖脚本,然后让 Angular 编译模态,以便它“知道”它。然而,尽管我在加载模式时按需定义了控制器,但 Angular 不会“意识到”它并引发错误(未捕获的错误:参数 'ControllerName' 不是函数,未定义) .
有没有办法让 Angular 识别我在运行时添加的新控制器?
这是我使用 fwiw 的模态代码(原型代码):
var directivesModule = angular.module('modal.directives', []);
directivesModule.directive("modal", function(ModalService) {
return function($scope, elem, attrs) {
elem.on("click", function(e) {
e.preventDefault();
var url = $(this).attr('href');
ModalService.load(url, $scope);
});
};
});
var servicesModule = angular.module('modal.service', []);
servicesModule.factory('ModalService', function ($http, $compile, $rootScope)
{
var ModalService = {};
ModalService.load = function(url, scope)
{
if ($('.modal[id="'+url+'"]').length > 0)
{
ModalService.show($('.modal[id="'+url+'"]'), scope);
return;
}
$http.get(url).success(function (data) {
var _data = $(data);
if (_data.find(".modal-body").length == 0) {
var _data = $('<div class="modal-header">'
+ '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>'
+ '<h3>'+_data.find(".title.hidden").text()+'</h3></div>'
+ '<div class="modal-body">'+data+'</div>'
+ '<div class="modal-footer">'
+ '<button class="btn btn-close">Close</button></div>');
}
var _scripts = [];
var scripts = _data.find("script");
if (scripts.length > 0)
{
scripts.each(function()
{
var elem = $(this);
if (elem.attr("src"))
{
_scripts.push(elem.attr("src"));
elem.remove();
}
});
}
ModalService.elem = $('<div class="modal hide fade" id="'+url+'">');
ModalService.elem.append(_data);
ModalService.elem.appendTo("body");
if (scripts.length > 0)
{
$.getScript(_scripts, ModalService.show.bind(this, ModalService.elem, scope));
}
else
{
ModalService.show(ModalService.elem, scope);
}
});
};
ModalService.show = function(elem, scope)
{
$rootScope.$broadcast('$routeChangeSuccess');
$compile(elem)(scope);
elem.modal();
elem.find(".btn-close").click(function() {
elem.modal("hide");
setTimeout(function() { elem.remove(); }, 500);
});
};
return ModalService;
});