直接上完整代码:
<html>
<head>
<meta charset="utf-8">
<title>angularjs对于不同module间的依赖注入</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" href="https://www.orchome.com/css/bootstrap/3.0.3/bootstrap.min.css"/>
<script src="https://www.orchome.com/user/js/angular-1.5.8.min.js"></script>
</head>
<body>
<div ng-app="myApp3" ng-controller="c2">
<h1>Hello {{pp}}</h1>
</div>
<div ng-view style="color: #81d0e8"></div>
<script>
angular.module('myApp3', ['myApp1','myApp2']);
angular.module('myApp2', [])
.controller('c2', function($scope, Chats) {
$scope.pp=Chats.all();
});
angular.module('myApp1', [])
.factory('Chats', function() {
return{
all: function() {
return '123';
}
}
});
</script>
</body>
</html>
1. 第一个module里定义一个factory
angular.module('myApp1', [])
.factory('Chats', function() {
return{
all: function() {
return '123';
}
}
});
2. 第二个module里定义一个controller,在这个controller里注入module1的factory,像以下这样写是不行的,要么在[ ]里写入对module1的依赖['myApp1'],要么再写一个module3同时依赖于module1和module2
angular.module('myApp2', [])
.controller('c2', function($scope, Chats) {
$scope.pp=Chats.all();
});
3. 写第三个module,同时依赖于module1和module2
angular.module('myApp3', ['myApp1','myApp2']);
然后在页面里调用module3的app和module2的controller,这样就行了
<div ng-app="myApp3" ng-controller="c2">
<h1>Hello {{pp}}</h1>
</div>