gpt4 book ai didi

javascript - 如何在 AngularJS 中动态加载 Controller ?

转载 作者:行者123 更新时间:2023-12-03 08:53:47 25 4
gpt4 key购买 nike

我的应用程序中有很多 Controller ,我不想预先加载它们,因为组合后的 JS 会变得非常繁重。

所以我尝试了以下方法:

在我的主 app.js 中,我的路由定义如下:

$routeProvider.when('/myaccount', {
templateUrl: 'my-account.html',
title: 'My Account'
})

my-account-controller.js 的 Controller 定义如下:

angular.module('myApp',[]).controller('my-account', ['$scope', function($scope) { 
$scope.greeting = 'Hola!';
}]);

最后在 my-account.html 中,我有一个脚本标记,它应该在使用 Controller 之前同步加载 Controller 。我使用 ng-controller 指令附加该 Controller :

script src='/assets/my-account-controller.js'
<div class="container" ng-controller='my-account'>
...
</div>

问题在于,Angular 无法将 my-account 识别为 Controller ,并抛出以下错误:

Error: [ng:areq] Argument 'my-account' is not a function, got undefined

谁能告诉我缺少的部分是什么?

最佳答案

您应该在 Controller 名称中使用 UpperCamelCase,我不知道您是否已经定义了 myApp,如果是,您应该从模块方法中删除第二个参数,因为它将重置依赖项:

所以这个 -> angular.module('myApp',[]) 应该是 -> angular.module('myApp')

angular.module('myApp').controller('MyAccount', ['$scope', function($scope) { 
$scope.greeting = 'Hola!';
}]);

在您看来:

<script src='/assets/my-account-controller.js'
<div class="container" ng-controller='MyAccount'>
...
</div>

路线:

$routeProvider.when('/myaccount', {
templateUrl: 'my-account.html',
title: 'My Account',
controller: 'MyAccount'
});

您可以阅读有关 Angular 最佳实践的更多信息 here

关于javascript - 如何在 AngularJS 中动态加载 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32588751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com