【问题标题】:Lazy loading of Angular controllers using RequireJS使用 RequireJS 延迟加载 Angular 控制器
【发布时间】:2014-03-15 16:11:41
【问题描述】:

我是 Angular 世界的新手,目前正在尝试为我们的 ASP.NET MVC 项目完成一个干净的设计,其中每个 Angular 控制器都在一个单独的文件中。我的问题是,是否可以延迟加载 Angular 控制器?我目前正在努力使用 RequireJS。我的概念证明代码如下:

CSHTML 视图 - Index.cshtml

<script src="~/Scripts/Controllers/mainController.js"></script> 
<div class="row" ng-controller="MainController">
    <div class="col-md-4">
        <span>{{1+1}}</span>

        Message Test: {{testmessage}}
        <button ng-click="ucase()">Upper</button>
</div>

_Layout.cshtml(第一行仅用于显示 ng-app)

<html ng-app="mainModule">

app.js

var mainModule = angular.module("mainModule", []);

ma​​inController.js

angular.module('mainModule').controller('MainController', ['$scope', function ($scope) {
    $scope.testmessage = "hello world!";
    $scope.ucase = function () {
        $scope.testmessage = angular.uppercase($scope.testmessage);
    }
}]);

如何摆脱 Index.cshtml 文件中对 mainController.js 的引用?有没有办法在需要时延迟加载控制器? RequireJS 可以帮忙吗?

【问题讨论】:

  • requirejs 可以用,我在一些老项目中用过。然而,这些天我更喜欢使用 grunt 并将所有 js 合并到一个包含在 html 中的 js 文件中。这允许将控制器、服务、指令分离到单独的文件中,并且避免使用 requirejs。
  • 这可能会对您有所帮助:ify.io/lazy-loading-in-angularjs

标签: asp.net-mvc angularjs requirejs


【解决方案1】:

最后,我能够使用 ocLazyLoader 在我的 POC 项目中实现 Angular 模块的延迟加载:

https://github.com/ocombe/ocLazyLoad

http://plnkr.co/edit/aGxuXMiPgYA0TFc67YL4(演示)

但是,我仍然不确定我们是否会继续实施。

【讨论】:

  • 不要犹豫,重新审视 ocLazyLoad,因为它最近有了很大的改进 :)
猜你喜欢
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
相关资源
最近更新 更多