簡體   English   中英

在ngView中加載Angularjs控制器

[英]Load Angularjs controllers in ngView

我是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>

對我來說顯而易見的是,我應該在配置module (MyApp)的確切位置定義controller ,這取決於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. [ng:areg] `childCtrl` is not a function. got undefined.

我也嘗試將script標簽放在div標簽之前的child.html ,但沒有任何影響。

現在我的問題是,當用戶路由到某個位置而不是在應用程序的開頭時,如何定義和加載OnDemand controller並完成繁重的工作?

您正在詢問延遲加載! 默認情況下,angular不支持延遲加載,該怎么辦? 您可以使用任何第三方庫,例如requirejs或其他。

目前angularjs不會在templateUrltemplate內部執行任何JavaScript, 更多詳細信息

這是一個使用requirejs進行延遲加載的工作示例。

也有一些關於onDemand腳本加載延遲加載angularjs的討論

在child.html頁面中,請勿包含ng-controller屬性。 child.html已經與childCtrl控制器關聯。 只需從child.html頁面中刪除ng-controller屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM