繁体   English   中英

在动态加载的HTML中使用角度控制器

[英]Use angular controller in dynamically loaded 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>

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

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

我假设您的动态内容具有一些模板。 我认为您应该看看angularjs中的脚本

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

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

如果您想即时加载模块,建议您使用ocLazyload。 在我的一个侧面项目中,这非常有效。

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

与路由器配合良好。

我发现了类似的问题如何包含特定于每个视图angularjs的javascript文件

    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. 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM