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

问题描述 投票:2回答:2

一切正常,但当我尝试将我的脚本分离到外部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。:外部文件链接和功能没有任何错误。

javascript angularjs angular-controller angularjs-1.6
2个回答
2
投票

这行创建了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 */

0
投票

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

使用以下代码实例化模块

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

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

angular.module('myApp').controller(/*.. Controller code ..*/)
© www.soinside.com 2019 - 2024. All rights reserved.