0

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>
Pete
  • 57,112
  • 28
  • 117
  • 166
ririzplus
  • 13
  • 3

2 Answers2

0

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.

Fire Bull
  • 227
  • 3
  • 10
  • Oh! Thanks!! but, I want to include subController in sub.html. No way to include subController in sub.html ? – ririzplus May 19 '15 at 08:58
0

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;
  };
}]);
Jan Peter
  • 380
  • 6
  • 16