2013-11-27 113 views
0

我正在制作一个角度应用程序,需要具有可在多个页面之间重复使用的模块。设置Angular指令

我做了成功创建一个菜单列表,但目前它已被注册为NG-应用它会坐在里面,像这样的部分指令:

angular.module('home', []) 
    .directive('Picks', function(){ 
    return { 
     restrict: 'E', 
     scope: false, 
     templateUrl: 'HTML/templateURL.html' 
    }; 
}); 

是的Angular的想法是,我的整个网站建立在一个页面/ ng-app包装上?或者,他们可以使这个Picks指令工作,而不需要为每个将放在其中的ng-app定义它的方式吗?

希望一切都有道理!

+0

您需要在您定义的每个'ng-app'上注册您的指令,但通常这只会是一个页面上的一个应用程序。当然,没有理由不能在一个页面上拥有多个独立的应用程序。 –

回答

0

在开发模式中,更喜欢使用单独的js文件作为指令。如果指令不依赖于家庭应用程序,那么它也可以在其他应用程序中重新注入。

//file component.js with directive usually alongside their Controllers 
var someModule = angular.module('business', []); 

someModule.directive('Picks', function(){ 
    return { 
     restrict: 'E', 
     scope: false, 
     templateUrl: 'HTML/templateURL.html' 
    }; 
}); 

/*file homepage.js inject the component module as a dependency*/ 
angular.module('home',['business']); 

/*file main.js another app*/ 
angular.module('myApp', ['business']); 


<!-- index.html --> 
<html ng-app="home"> 
... 
<script src="component.js"></script> 
<script src="homepage.js"></script> 
</html> 
<!-- eventually concat and minified for pre production, so it doesn t matter 
how you organized it 
--> 

在实践中,一些指令使用一些服务/工厂很多。所以他们最终在同一个模块中。这意味着按功能而不是按类型对模块进行分组。 这是一个选择的问题。

+0

感谢Mehery,这很有道理。在我未受教育的条件下:在自己的angular.module中注册指令,然后在需要时将该模块作为依赖项注入其他模块。 –