javascript - 在动态加载的 html 中使用 Angular Controller

标签 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";
        });
    }

}

任务.html

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

在动态加载的文件(由 ng-include 加载)中,我想定义该文件将使用的 Angular Controller 。

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

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

最佳答案

我假设您的动态内容有一些模板。我认为你应该看看script在 AngularJS 中

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

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

关于javascript - 在动态加载的 html 中使用 Angular Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37162799/

相关文章:

javascript - 有什么方法可以使用拖放以 Angular 上传 .ply、.STL、.obj 文件吗?

html - 如何使用 http 服务器流式传输 html mp3

javascript - 无法初始化 angularjs,包括 ng-controller

javascript - 文本输入仅允许angularjs中的整数输入

javascript - Node.js - 我将如何转发 HTTP 流量(反向代理)?

javascript - 检查字符串中特定位置是否存在数字

javascript - @davidjbradshaw 的 iframe-resizer,iframe 宽度不调整

javascript - html anchor 标记穿过屏幕

javascript - 在 HTML TABLE 中的每一行之后切换

css - 从生成的 html 中删除一个类项