【问题标题】:Load Angularjs controllers in ngView在 ngView 中加载 Angularjs 控制器
【发布时间】:2015-10-22 14:46:56
【问题描述】:

我是 Angular 的新手,刚开始构建一个测试项目来学习它,现在在加载控制器 OnDemand 时遇到问题。 让我们编码一下,我有以下 HTML:

index.html

<body>
    <div ng-app="MyApp">
        <a href="/child"> CLICK ME </a>
        <div ng-view></div>
    </div>
    <script>
        angular.module("MyApp",['ngRoute'])
            .config(function($routeProvider) {
                $routeProvider.when('/child', {
                    templateUrl: 'somwhere/child.html',
                    controller: 'childCtrl' <!-- will remove -->
                });
            }) <!-- will remove contoller defination below -->
            .controller('childCtrl', function($scope) {
                $scope.data = DoHeavyCalc();
            });
    </script>
</body>

对我来说很明显的是我应该定义我的controller我在哪里配置我的module(MyApp),这样做取决于DoHeavyCalc(),现在不需要! (认为​​这个方法计算量很大,但它应该只在用户点击链接时运行,而不是在应用程序开始时运行)。

现在我想在child.html 中加载并定义控制器,而不是我的index.html。好的,所以我删除了上面代码中标记的部分并尝试像这样编写child.html

child.html

<div ng-controller="childCtrl">
    {{data}}
</div>
<script>
    angular.module("MyApp")
        .controller('childCtrl', function($scope) {
            $scope.data = DoHeavyCalc();
        });
</script>

但是会导致错误: [ng:areg] `childCtrl` is not a function. got undefined.

我也尝试将script标签放在child.html之前div标签,但它没有影响任何东西。

现在我的问题是,我如何定义和加载 controller OnDemand 并在用户路由到某个位置而不是在应用程序开始时完成我的繁重工作?

【问题讨论】:

    标签: javascript html angularjs web


    【解决方案1】:

    您在询问延迟加载!默认情况下 Angular 不支持延迟加载,你能做什么?您可以使用任何第三方库,例如 requirejs 或其他库。

    目前 angularjs 不会在 templateUrltemplatemore details 中执行任何 javascript

    这是一个使用 requirejs 的 lazy loading 的工作示例。

    还有一些关于 onDemand 脚本加载的讨论 Lazy loading angularjs

    【讨论】:

      【解决方案2】:

      在 child.html 页面中不包含 ng-controller 属性。 child.html 已经与 childCtrl 控制器相关联。只需从 child.html 页面中删除属性 ng-controller

      【讨论】:

      • 有效吗? OP 谈论 onDemand 脚本加载的地方。 child.html 如何与 childCtrl 关联,他想从路由中删除该控制器定义?
      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 2013-08-27
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      相关资源
      最近更新 更多