【问题标题】:Use angular controller in dynamically loaded html在动态加载的 html 中使用角度控制器
【发布时间】:2016-05-13 15:45:26
【问题描述】:

我有以下代码

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

如何更改我的代码来解决这个问题?

【问题讨论】:

标签: javascript html angularjs


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    适用于路由器。

    【讨论】:

      【解决方案3】:

      我发现了类似的问题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. 
      

      有人能证实一下这篇论文吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        • 2016-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多