mercredi 21 octobre 2015

Load Angularjs controllers in ngView

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:

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>

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:

child.html

<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.

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?




Aucun commentaire:

Enregistrer un commentaire