javascriptangularjsangular-controllerangularjs-1.6

How to split an AngularJS code in separate files?


Everything is working but when I try to separate my script to external js files, AngularJS is not running.

Here is my script:

<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>

I separated like:

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

but didn't work.

Also, I separated like:

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

but didn't work again.

How is possible to separate this AngularJS?

P.S.: There aren't any mistakes on the external file link and functions.


Solution

  • This line creates the module MyApp, because of the [...] part:

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

    As you want to create a controller for this module, you will need to refer to it. In your app, you do it directly after the module declaration:

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

    So you create the module and the controller in one line.


    Now what you need is to separate it, so, firstly create your module:

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

    In another file, create a controller on this module, with the following synthax:

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