Angularjs Modules - Packaging Directives and Their Controllers

243 views Asked by At

I have the following javascript code and i ran into a issue:

My .js file

angular.module('MyApp',['ngMaterial','ngMessages'])
.controller('MainCtrl',['$mdDialog',function($mdDialog'){
this.openDialog = openDialog;

function openDialog() {
....... my codes ...... 
    }
)])
.controller('SubCtrl',function($scope){

   my codes.

})

.directive('test',function(){
    return {
        controller: 'MainCtrl' ,
        scope: { } ,
        templateUrl: 'Button.html'
     }
})

Currently, I am using the controller 'MainCtrl' in my directive. But is it possible to put all the controller into the directive and still make it run as per normal usage??

what I want in my final .js File

.directive('test',function(){

my controllers all here <-- unsure of the syntax.

}
2

There are 2 answers

2
georgeawg On BEST ANSWER

In the end i would need to package my directive into a .js file so that my classmates can use it just by calling the directive name and putting in the .js file of the directive

To package the directive and controller into a single module:

sai.js

angular.module("saiModule",[]);

angular.module("saiModule").controller("saiController",function() {
    //Put controller code here
});

angular.module("saiModule").directive("saiDirective", function() {
    //Put directive code here
});

Then classmates use it by adding the module as a dependency to their apps:

JS

angular.module("myApp", ["saiModule"]);

HTML

<sai-directive></sai-directive>

Services, filters, providers, constants, etc. can also be added to the module.

For more information, see AngularJS Module API Reference.

5
Sai On

You can simply do like this by putting function inside of directive:

.directive('test',function(){
    return {
        controller: function('$mdDialog'){
            this.openDialog = openDialog;

            function openDialog() {
                ....... my codes ...... 
            } 
        },
        scope: { } ,
        templateUrl: 'Button.html'
     }
})