在动态加载的html

时间:2016-05-11 12:31:11

标签: javascript html angularjs

我有以下代码

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>

在动态加载的文件中(由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

如何更改代码以解决此问题?

3 个答案:

答案 0 :(得分:2)

我假设你的动态内容有一些模板。我想你应该看看angularjs中的script

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

并使用ui-routing添加动态内容,在路由器中分配控制器。

答案 1 :(得分:0)

如果你想动态加载模块我推荐ocLazyload。这在我的一个项目中运作良好。

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

适用于路由器。

答案 2 :(得分: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. 

有人可以证实这个论点吗?