Angularjs 不同模块中的angular.js指令
我很困惑。如果我每页只能使用Angularjs 不同模块中的angular.js指令,angularjs,Angularjs,我很困惑。如果我每页只能使用ng app一次,那么如何使用位于不同模块、不同.js文件中的指令呢。看: <script src='mainModule.js'/> <script src='secondModule.js'/> <body ng-app='mainModule'> <my-thingy/> <div> <other-thingy/> </div> </body
ng app
一次,那么如何使用位于不同模块、不同.js文件中的指令呢。看:
<script src='mainModule.js'/>
<script src='secondModule.js'/>
<body ng-app='mainModule'>
<my-thingy/>
<div>
<other-thingy/>
</div>
</body>
mainModule.js:
angular.module("mainModule",[]).directive("myThingy",function(){ ... })
secondModule.js:
angular.module("secondModule",[]).directive("otherThingy",function(){ ... })
mainModule.js:
angular.module(“mainModule”,[]).directive(“myThingy”,function(){…})
secondModule.js:
angular.module(“secondModule”,[]).directive(“otherThingy”,function(){…})
那么,我现在如何指向页面上的第二个模块,而不从mainModule.js引用它呢?有一个解决方案,可以通过编程方式在页面上引导几个角度模块() 您必须从html中删除
ng app
属性
定义几个模块:
var app1 = angular.module('myApp1', []);
var app2 = angular.module('myApp2', []);
app1.controller('MainCtrl', function($scope) {
$scope.name = 'App1';
});
app2.controller('MainCtrl', function ($scope) {
$scope.name = 'App2';
})
然后在index.html中执行以下操作:
<html>
<head></head>
<body>
<!-- Module 1 -->
<div id="myApp1">
<div ng-controller="MainCtrl">
<h1>Hello {{name}}</h1>
</div>
</div>
<!-- Module 2 -->
<div id="myApp2">
<div ng-controller="MainCtrl">
<h1>Hello {{name}}</h1>
</div>
</div>
<!-- Bootstrap modules -->
<script>
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('myApp1'), ['myApp1']);
angular.bootstrap(document.getElementById('myApp2'), ['myApp2']);
});
</script>
</body>
</html>
你好{{name}
你好{{name}
元素(文档).ready(函数(){
bootstrap(document.getElementById('myApp1'),['myApp1']);
bootstrap(document.getElementById('myApp2'),['myApp2']);
});
下面是使用此解决方案的示例。@Agzam,只需创建第三个顶级应用程序模块,该模块将依赖于包含指令的子模块。:
<script src='mainModule.js'/>
<script src='secondModule.js'/>
<script>
angular.module('app', ['mainModule', 'secondModule'])
</script>
<body ng-app='app'>
<my-thingy/>
<div>
<other-thingy/>
</div>
</body>
角度.module('app',['mainModule','secondModule']))
我认为这不是一个好的解决方案,因为它会启动两个完全分离的AngularJS应用程序。除此之外,它还禁止一些用例(例如,如果我想使用两个指令,一个指令在另一个指令中?你能在不将指令绑定到任何模块的情况下以某种方式重用指令吗?实际上不能。这是@pkozlowski.opensource指出的弱点。他在他的answer@Agzam:是的,您可以编写未绑定到任何自定义模块的指令。它们仍然绑定到一些模块是ng
模块。这些指令可以在任何自定义应用程序模块页面上访问,也可以在那些只设置
而不指定任何特定应用程序模块的页面上访问。