2016-05-11 144 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. 

有人能证实这一论断?