如何在单独的文件中拆分 AngularJS 代码?

How to split an AngularJS code in separate files?

一切正常,但是当我尝试将我的脚本分离到外部 js 文件时,AngularJS 不是 运行。

这是我的脚本:

<script>
angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('AppCtrl', function ($scope) {
    $scope.isDisabled = true;
    $scope.UnitReport = function(){
        alert("aa");
    }
})
//this is just a part of script
;
</script>

我是这样分开的:

.controller('AppCtrl', function ($scope) {
    $scope.UnitReport = function(){
        alert("aa");
    }
})

但没用。

还有,我是这样分开的:

angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('AppCtrl', function ($scope) {
    $scope.UnitReport = function(){
        alert("aa");
    }
})

但又没用。

这个AngularJS怎么可能分开?

P.S.: 外部文件link和函数都没有错误。

是的,可以在不同的js上分开文件。

使用以下代码实例化模块

angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])

为了获取现有模块并向其添加新控制器,您应该只使用一个参数,即模块名称。

angular.module('myApp').controller(/*.. Controller code ..*/)

这一行 创建 模块 MyApp,因为 [...] 部分:

angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache']);

因为你想为这个模块创建一个控制器,你需要参考它。在您的应用程序中,您可以在模块声明之后直接执行此操作:

angular.module('MyApp', [...]).controller(...);

所以你在一行中创建了模块和控制器


现在你需要的是分离它,所以,首先创建你的模块:

angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache']);

在另一个文件中,使用以下语法在此模块上创建一个控制器:

angular.module('MyApp').controller(...); /* There are no [] anymore -> not a mod creation */