【发布时间】: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