Search code examples
angularjsangularjs-directiveangularjs-controllerangularjs-module

Angularjs Modules - Packaging Directives and Their Controllers


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.

}

Solution

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