2016-05-11 148 views
0

我有以下代碼在動態加載的HTML使用角度控制器

app.js

var app = angular.module('myModule', ['schemaForm', 'base64', 'ngRoute']); 

taskController.js

app.controller('TaskController', function($scope, AuthService, $http, $base64, $location) { 
    $scope.fetchFormKey = function() { 
     $http.defaults.headers.common['Authorization'] = 'Basic ' + AuthService.auth; 
     $http.get(restServerURL + '/task/' + $scope.taskId + '/form'). 
     success(function(data) { 
      $scope.formKey = "./partials/itpTrainingCreation/" + data.key + ".html"; 
     }); 
    } 

} 

task.html

<h2>Generated form</h2> 
<div ng-controller="TaskController" ng-init="fetchFormKey()"> 
    <div ng-include src="formKey"></div> 
</div> 

在動態加載文件(loade d by ng-include)我想定義這個文件將要使用的角度控制器。

dynamic.html(例如)

<script> 
angular.module('myModule').controller('DymanicController', function($scope, AuthService, $http, $base64, $location) { 
$scope.exampleValue="myCustomValue"; 
}); 
</script> 
<div ng-controller="DymanicController"> 
    {{exampleValue}} 
</div> 

不幸的是我得到以下錯誤: http://errors.angularjs.org/1.5.5/ng/areq?p0=DymanicController&p1=not%20a%20function%2C%20got%20undefined

我怎樣才能改變我的代碼來解決這個問題?

+0

http://stackoverflow.com/questions/15250644/loading-an-angularjs-controller-dynamically – Thalaivar

回答

0

如果你想加載模塊,我建議ocLazyload。這在我的一個項目中工作得很好。

myApp.controller("MyCtrl", function($ocLazyLoad) { 
    $ocLazyLoad.load('testModule.js'); 
}); 

適用於路由器。

0

我假設你的動態內容有一些模板。我想你應該看看script在angularjs

<script type="text/ng-template" id="/tpl.html"> 
    Content of the template. 
</script> 

,並使用UI路由添加動態內容,有路由器分配控制器。

0

我發現類似的問題how to include javascript file specific to each view angularjs

You can't. Angular does not load javascript parts from a template. 
    What you should do is to include them in your main application anyway. 
    All of the controllers should be loaded while the main app is initiating. 

有人能證實這一論斷?