0
votes

following code create error like this

Uncaught Error: [ng:areq] http://errors.angularjs.org/1.3.15/ng/areq?p0=subCtrl&p1=not%20a%20function%2C%20got%20undefined

how can i fix it?

sample code here http://plnkr.co/edit/i3KmuFd09puvCyfqoX39?p=preview

index.html

  var myapp = angular.module("myapp",[]);
  myapp.controller( "mainCtrl" , ["$scope","$compile",function($scope,$compile){
    var p = $scope;
    p.getSub = function() {
      var url = "sub.html";
      $.ajax({url:url,success:function(html) {
                    $("#content").html(html);
                    $compile(html)($scope);
      }});
    }
  }]);


<body ng-controller="mainCtrl">
    <button ng-click="getSub()">getSub</button>
    <div id="content">
       sub.html
    </div>
</body>

sub.html

<script>
    myapp.controller( "subCtrl" , ["$scope",function($scope){
    alert("subCtrl created");
}]);  
</script>

<div ng-controller="subCtrl">
  sub.html loaded.
</div>
2
The error you get from angular says that your subCtrl is not defined.Hinrich
why don't you use something like ng-include or a directive?Jan Peter
I would suggest using a directive for this as Jan Peter suggestedEugene J. Lee

2 Answers

0
votes

the problem is in the nested controllers. So you use "main" controller with $compile, and in the very next time you include nested controller in the same html.
So the solution is: $.ajax({url:url,success:function(html) { $("#content").html(html); $compile(html)($scope); alert("subCtrl created"); }});
and in the sub.html:
<div> sub.html loaded. </div>

Good luck.

0
votes

in HTML:

<body ng-controller="mainCtrl">
  <button ng-click="getSub()">getSub</button>
  <div ng-if="showSub">
    <div ng-include="{{mySub}}.html"></div>
  </div>
</body>

your controller:

myapp.controller( "mainCtrl" , ["$scope",function($scope){
  $scope.showSub = false;
  $scope.mySub = '';
  $scope.getSub = function(){
    $scope.mySub = "sub";  // change this to include other files
    $scope.showSub = true;
  };
}]);