I'm new to Angular and just started to build a test project to learn it, now have a problem with loading controllers OnDemand . let's code a bit, I have the following 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>
what is obvious to me is that I should define my controller
exactly where I config my module
(MyApp) , which doing this depends on DoHeavyCalc()
which is not needed right now! (think this method does a big calculation, but it should be run only when the user clicks on the link, not at the beginning of the app).
Now I want to load the and define the controller inside child.html
instead of my index.html
. OK, so I removed the sections marked in above code and tried to write the child.html
like this:
<div ng-controller="childCtrl">
{{data}}
</div>
<script>
angular.module("MyApp")
.controller('childCtrl', function($scope) {
$scope.data = DoHeavyCalc();
});
</script>
but is causes an error: [ng:areg] `childCtrl` is not a function. got undefined.
[ng:areg] `childCtrl` is not a function. got undefined.
also i tried to put script
tag in child.html
before the div
tag, but it didn't affect anything.
Now my question is, how can i define and load the controller
OnDemand and do my heavy work just when the user routes to a certain location not at the beginning of app?
You are asking about lazy loading ! By default angular doesn't support lazy loading, what you can do ? you can use any third party library like requirejs
or others.
Currently angularjs doesn't execute any javascript inside templateUrl
or template
, more details
Here is a working example of lazy loading using requirejs.
Also there is some discussion regarding onDemand script loading Lazy loading angularjs
In the child.html page do not include ng-controller attribute. Already child.html is associated with the childCtrl controller. Just remove the attribute ng-controller from the child.html page
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.