javascript - 将 Controller 注入(inject)正在运行的 Angular 应用程序

标签 javascript angularjs

我编写了一些简单的代码,允许引导模态与 Angular 一起使用,因为它在单击时将链接加载到模态中。现在,相关链接有自己的 Angular Controller ,这些 Controller 包含在其源代码中。当加载模态时,我首先使用 jquery 加载所有它的依赖脚本,然后让 Angular 编译模态,以便它“意识到”它。然而,尽管我在加载模态时按需定义了 Controller ,但 Angular 不会“意识到”它并抛出错误(未捕获错误:参数“ControllerName”不是函数,未定义) .

有没有办法让我告诉 Angular 识别我在运行时添加的新 Controller ?

这是我使用 fwiw 的模态代码(原型(prototype)代码):

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;
});

最佳答案

是的,这是可能的,并且所有需要的实用程序都已包含在 Angular 中。我无法编写现成的代码,但这里可以给您一个想法:

  1. 加载 HTML 代码,可能直接加载到 DOM 中 - 类似于 $('#myDiv').load('dialog.html')。不要将 Controller 与 ng-controller 绑定(bind)!保存对 DOM 节点的引用(我们称之为 element)。

  2. 加载你的 Controller ——可能是 head.js或最适合您情况的任何内容。保存对 Controller 函数的引用(controller 是个好名字)。您不需要在 Angular 应用程序中注册它,只需一个简单的全局函数即可。像往常一样引用任何所需的服务和范围:

function MyCtrl($scope, $resource, $http, $whatever, YourOwnService) {
    $scope.hello = 'world';
}
  1. 连接起来:
function ($compile, $rootScope, $inject) {
    var element = angular.element('#myDiv'),
        controller = MyCtrl;

    // We need new scope:
    var $scope = $rootScope.$new(true);

    // Compile our loaded DOM snippet and bind it to scope:
    $compile(element)($scope);

    $inject.invoke(controller, {
        $scope:$scope // you can add any other locals required by your controller
    });
}

我不能保证这段代码能按原样工作,但它描述了我几周前使用过的技术。但我必须警告您,这将不允许您动态添加 AngularJS 依赖项:您的应用程序应包含在引导应用程序之前添加的所有可能的模块。

关于javascript - 将 Controller 注入(inject)正在运行的 Angular 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16379871/

相关文章:

javascript - 无法使用 "class"方法在 JavaScript 中进行回调

javascript - 最好的 JavaScript 日期解析器和格式化程序?

angularjs - ServiceNow angularjs : how to pass server script values to client script

javascript - String.fromCodePoint() 在 IE 中不起作用,Tab 键在 Firefox 中不起作用

javascript - D3js 具有节点和链接的拖动行为

javascript - 在 silverstripe CMS 中,按下时在 TextareaField 中添加一个选项卡

javascript - IE9 javascript 问题的占位符脚本

javascript - AngularJS ng 类不起作用

javascript - 在 Angularjs 中添加新行后如何以编程方式关注下一个单元格

angularjs - 如何使用 Angular 1.4 注入(inject) HTML?