不同模块中的 angular.js 指令 [英] angular.js directives in different modules
问题描述
我很困惑.如果我每页只能使用一次 ng-app
,我该如何使用位于不同模块、不同 .js 文件中的指令.看:
<script src='secondModule.js'/><body ng-app='mainModule'><我的东西/><div><其他东西/>
主模块.js:angular.module("mainModule",[]).directive("myThingy",function(){ ... })第二个模块.js:angular.module("secondModule",[]).directive("otherThingy",function(){ ... })
那么,我现在如何指向页面上的 secondModule,而不从 mainModule.js 中引用它
有一个以编程方式在页面上引导多个 angular 模块的解决方案 ( 文档).
您必须从 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 中做:
<头></头><身体><!-- 模块 1 --><div id="myApp1"><div ng-controller="MainCtrl"><h1>你好{{name}}</h1><!-- 模块 2 --><div id="myApp2"><div ng-controller="MainCtrl"><h1>你好{{name}}</h1>
<!-- 引导模块--><脚本>angular.element(document).ready(function() {angular.bootstrap(document.getElementById('myApp1'), ['myApp1']);angular.bootstrap(document.getElementById('myApp2'), ['myApp2']);});</html>
这是使用此解决方案的有效 plnkr.
I am confused. If I can use ng-app
only once per page how can I use directives that sit in different modules, in different .js files. Look:
<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(){ ... })
So, how do I now point to the secondModule on the page, without referencing it from mainModule.js
There is a solution to bootstrap several angular modules on a page programmatically ( docs ).
You have to remove ng-app
attribute from html.
Define several modules:
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';
})
And then in index.html do:
<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>
Here is a working plnkr with this solution.
这篇关于不同模块中的 angular.js 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!