Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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>
share|improve this question
    
The error you get from angular says that your subCtrl is not defined. – Hinrich May 19 '15 at 8:11
    
why don't you use something like ng-include or a directive? – Jan Peter May 19 '15 at 8:22
    
I would suggest using a directive for this as Jan Peter suggested – Eugene J. Lee May 19 '15 at 8:23

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.

share|improve this answer
    
Oh! Thanks!! but, I want to include subController in sub.html. No way to include subController in sub.html ? – ririzplus May 19 '15 at 8:58

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;
  };
}]);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.