Angularjs模块 - 包装指令及其控制器

时间:2017-01-06 06:43:06

标签: angularjs angularjs-directive angularjs-controller angularjs-module

我有以下javascript代码,我遇到了一个问题:

我的.js文件

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'
     }
})

目前,我正在使用控制器' MainCtrl'在我的指令中。但是是否可以将所有控制器放入指令中并仍按正常使用方式运行?

我想要的最终 .js文件

.directive('test',function(){

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

}

2 个答案:

答案 0 :(得分:0)

你可以通过将函数放在指令中来完成这样的操作:

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

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

答案 1 :(得分:0)

  

最后我需要将我的指令打包成一个.js文件,这样我的同学就可以通过调用指令名称并输入指令的.js文件来使用它

将指令和控制器打包到一个模块中:

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
});

然后同学通过将模块添加为其应用程序的依赖项来使用它:

JS

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

HTML

<sai-directive></sai-directive>

服务,过滤器,提供程序,常量等也可以添加到模块中。

有关详细信息,请参阅AngularJS Module API Reference