3

一切正常,但是当我尝试将我的脚本与外部 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?

PS:外部文件链接和功能没有任何错误。

4

2 回答 2

3

由于部分原因,这一行创建了模块: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 */
于 2017-06-21T13:13:16.553 回答
0

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

使用以下代码实例化模块

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

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

angular.module('myApp').controller(/*.. Controller code ..*/)
于 2017-06-21T12:45:08.333 回答