在ngView中加载Angularjs控制器

Load Angularjs controllers in ngView

本文关键字:Angularjs 控制器 加载 ngView      更新时间:2023-09-26

我是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和做我的繁重的工作,只是当用户路由到某个位置,而不是在应用程序的开始?

您正在询问延迟加载!默认情况下,angular不支持延迟加载,你该怎么办?您可以使用任何第三方库,如requirejs或其他。

目前angularjs不会在templateUrltemplate内部执行任何javascript,更多细节

下面是一个使用requirejs延迟加载的工作示例。

也有一些关于onDemand脚本加载的讨论延迟加载angularjs

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