3

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.

Mistalis
  • 17,793
  • 13
  • 73
  • 97
Emirhan
  • 132
  • 8

2 Answers2

3

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 */
Mistalis
  • 17,793
  • 13
  • 73
  • 97
0

Yes, it is possible to separate files on different js.

With the following code you instantiate the module

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

In order to grab the existing module and add a new controller to it you should use only one argument, which is the name of the module.

angular.module('myApp').controller(/*.. Controller code ..*/)
bruno.bologna
  • 475
  • 4
  • 14