2017-09-22 8 views
0

すべてのモジュールを最初に宣言しました&が私のメインコントローラへの依存として追加されました& requirejsを介して動的に他のモジュールをロードしたいと思っています。私はルーティングメカニズムを使用していません。angularJSのrequire.jsに子モジュールを注入する

mainController.js

angular.module('ChildModule',[]); 
 
angular.module('UConnect',['ChildModule']).controller('ParentController',['$scope','$timeout','$compile',function($scope,$timeout,$compile){ 
 
    $scope.name = "Parent Controller"; 
 
    $scope.loadController = function(){ 
 
     require(["controller/childController"],function(){ 
 
     $timeout(function(){ 
 
      var element = angular.element(document.querySelector('#addViewsHere')); 
 
      var html = '<div ng-include="\'templates/childView.html\'"></div>'; 
 
      element.append(html); 
 
      $compile(element.contents())($scope); 
 
     }) 
 
     }); 
 
    } 
 
}]);

index.htmlを

<!DOCTYPE html> 
 
<html ng-app="UConnect"> 
 
    <head> 
 
    <meta charset="utf-8"> 
 
    <title></title> 
 
    </head> 
 
    <script type="text/javascript" src="js/angular-1.5.7.min.js"></script> 
 
    <body> 
 
    <div ng-controller="ParentController"> 
 
     <h1>{{name}}</h1> 
 
     <button type="button" name="button" ng-click="loadController();">Click to load controller</button> 
 
     <div id="addViewsHere"></div> <!-- Adding views here dynamically --> 
 
    </div> 
 
    </body> 
 
    <script src="js/app.js" charset="utf-8"></script> 
 
    <script data-main="js/main.js" type="text/javascript" src="js/require.js"></script> 
 
</html>

childController.js

define('childDefine',[],function() { 
 
    angular.module('ChildModule').controller('childController',['$scope',function($scope){ 
 
     $scope.name = "Sumeet"; 
 
     $scope.callChildController = function(){ 
 
     alert('child clicked'); 
 
     }; 
 
    }]); 
 
});

childView.html

<div ng-app="ChildModule" ng-controller="childController"> 
 
    <h1>Child Controller</h1> 
 
    <button type="button" name="button" ng-click="callChildController();">Call Child Controller</button> 
 
    <h1>{{childName}}</h1> 
 
</div>

私はボタンをクリックすると私はビューをロードしています、その後、それがrequireJS &児コントローラをロードしますng-include。

これはコンソールエラー&を表示していましたが、両方のビュー&コントローラが動作していません。 enter image description here

答えて

0

AngularJSにモジュールを動的にロードするビルドイン方法はありません。

しかし、これを可能にするlib oclazyloadがあります。

関連する問題