angularjs - 从模板( View )中动态加载 AngularJS 模块

标签 angularjs angular-routing angular-template

背景:为了便于论证,我们假设您有 100,000 次观看(部分观看)。我们还假设您有附带的 View 范围 Controller ,以及潜在的 View 范围服务和过滤器。尝试设想一个托管 100,000 个不同小型应用程序的聚合应用程序。

问题:当您有需要附带 Controller 的“部分”时,典型的解决方案是执行以下操作:

$routeProvider.when('/app1', {
        templateUrl: 'partials/view1.html',
        controller: 'controller1'
    });

Controller 通常通过以下方式从index.html加载:

<script src="js/directives/Controller1.js"></script>

这种方法的问题在于它无法扩展。有一些动态加载 Controller 的解决方案,但它们仍然需要在各种配置中添加触摸点。

理想的解决方案:理想情况下,对于编号为 000 的非常小的应用程序, Controller 可以从部分本身内部动态加载。这将减轻管理多个文件和多个配置接触点(更不用说网络请求)的需要,并很好地控制每个部分。

它看起来像这样:

在路由器中:

$routeProvider.when('/apps/:appId', {
        templateUrl: 'partials/app-frame.html',
        controller: 'AppCtrl'
    });

在包含 html(应用程序框架)中包含相对不同的“迷你应用程序”:

<h1>Currently hosting {{appId}}</h1><hr>
<div class="ng-include: appUrl"></div>

在使用 appUrl 进行部分解析时,将 Controller 标记定义为一个:

<script>
  myApp.controller('controller1', ['$scope', function ($scope) {
    $scope.foo = "bar";
  }]);
</script>


<div ng-controller="controller1">
     {{foo}}
</div>

对于像这样的情况, Controller 和 View 有很多部分和 1-1 映射,将两者结合起来以提高开发效率和维护是有意义的。它比使用多个文件和额外的配置接触点要干净得多。

问题是,这行不通。它可以像在应用指令之前强制加载脚本一样简单......但不确定如何做到这一点?

以下是该问题的一些类似解释:

https://groups.google.com/forum/#!topic/angular/H4haaMePJU0

Loading Partial Page With Angular and Compile The Controller

AngularJS 团队的 Igor 说:

I see.. we looked into supporting script tags in jqlite, but what needs to be done to get a cross-browser support involves a lot of black magic. For this reason we decided that for now we are just going to recommend that users use jquery along with angular in this particular case. It doesn't make sense for us to rewrite one third of jquery to get this working in jqlite.

但我不知道他所说的“使用jquery”是什么意思...JQuery 已经从index.html(以及在 angularjs 之前)加载到应用程序中,但听起来我需要在部分本身内专门做一些事情。

最佳答案

您无法在 AngularJS 引导之后通过 module('app').controller(name, function() { .. }) 添加新 Controller 。为了使其正常工作,您应该使用 $controllerProvider.register(name, function() { .. })

您可以通过以下方式覆盖原始 Controller 注册功能,以便能够在 Bootstrap 前和后添加 Controller :

var app = angular.module('app', [
    'ui.router'
]);

app.config(function($controllerProvider) {
    app.controller = function (name, controller) {
        $controllerProvider.register(name, controller);
    };
});

关于angularjs - 从模板( View )中动态加载 AngularJS 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19779687/

相关文章:

namespaces - 角达特 : Namespace of route names hierarchical too?

angular - 带有用户单击选定组件的动态选项卡

javascript - 为什么 Angular 使用闭包来定义指令和其他核心语法?

javascript - 如何在 AngularJS 指令中绑定(bind)属性?

javascript - AngularJS “Wire up a Backend” 应用程序未在编辑对话框中加载数据 - 使用最新的 firebase

Angular 渲染的 DOM html 自定义属性

angularjs - Angular 将文件上传到 AWS S3 错误 412 PreconditionFailed

asp.net-mvc-4 - Angular.js 和 ASP.NET MVC 4

javascript - 如何使用没有尾部斜杠的 UI-Router 定义可选参数?