0

以下代码创建这样的错误

未捕获的错误:[ng:areq] http://errors.angularjs.org/1.3.15/ng/areq?p0=subCtrl&p1=not%20a%20function%2C%20got%20undefined

我该如何解决?

示例代码在这里 http://plnkr.co/edit/i3KmuFd09puvCyfqoX39?p=preview

索引.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>

子.html

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

<div ng-controller="subCtrl">
  sub.html loaded.
</div>
4

2 回答 2

0

问题出在嵌套控制器中。因此,您将“主”控制器与 $compile 一起使用,并在下一次将嵌套控制器包含在同一个 html 中。
所以解决方案是: $.ajax({url:url,success:function(html) { $("#content").html(html); $compile(html)($scope); alert("subCtrl created"); }});
在sub.html中:
<div> sub.html loaded. </div>

祝你好运。

于 2015-05-19T08:29:06.180 回答
0

在 HTML 中:

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

你的控制器:

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;
  };
}]);
于 2015-05-19T08:34:22.253 回答