所有
我对Angular很新,我想知道当我包含多个模块时,如果有相同的名称控制器/服务等,角度如何决定使用哪一个?
由于
答案 0 :(得分:1)
这是Angular模块系统的一个限制。解决依赖关系时的操作顺序是:
想象一下以下设置:
angular.module('alpha', [])
.service('fooService', fooService);
angular.module('beta', [])
.service('fooService', someOtherFooService);
angular.module('my-app', ['alpha', 'beta']);
在这种情况下,someOtherFooService
将始终是在您的应用程序中请求它时注入的依赖项。
现在,如果我们将上述示例修改为:
angular.module('alpha', [])
.service('fooService', fooService);
angular.module('my-app', ['alpha'])
.service('fooService', myFooService);
然后myFooService
将始终是注入的那个,因为它是主要模块。
您可以在下面的示例中看到更详尽的示例。
(function() {
function serviceFactory(msg) {
return function() {
this.sayHello = function() {
return msg;
};
}
}
function rollupService(alphaService, betaService, gammaService, deltaService) {
this.rollup = function() {
return [
alphaService.sayHello(),
betaService.sayHello(),
gammaService.sayHello(),
deltaService.sayHello(),
].join(" | ");
};
}
angular.module('alpha', [])
.service('alphaService', serviceFactory("alpha module"))
.service('betaService', serviceFactory("alpha module"))
.service('gammaService', serviceFactory("alpha module"))
.service('deltaService', serviceFactory("alpha module"))
.service('rollupService', rollupService)
.run(function(rollupService, $rootScope){
$rootScope.rollup = rollupService.rollup();
});
angular.module('beta', [])
.service('betaService', serviceFactory("beta module"))
.service('gammaService', serviceFactory("beta module"))
.service('deltaService', serviceFactory("beta module"))
angular.module('gamma', [])
.service('gammaService', serviceFactory("gamma module"))
.service('deltaService', serviceFactory("gamma module"))
angular.module('my-app', ['alpha', 'beta', 'gamma'])
.service('deltaService', serviceFactory("my-app module"))
.controller('myCtrl', function(alphaService, betaService, gammaService, deltaService) {
this.alphaService = alphaService;
this.betaService = betaService;
this.gammaService = gammaService;
this.deltaService = deltaService;
});
}());

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="my-app" ng-controller="myCtrl as ctrl">
<h3><code>alphaService.sayHello() = </code>{{ctrl.alphaService.sayHello()}}</h3>
<h3><code>betaService.sayHello() = </code>{{ctrl.betaService.sayHello()}}</h3>
<h3><code>gammaService.sayHello() = </code>{{ctrl.gammaService.sayHello()}}</h3>
<h3><code>deltaService.sayHello() = </code>{{ctrl.deltaService.sayHello()}}</h3>
<hr />
<p>Alpha modules dependencies are controller by the application, not how it defined
it's own dependencies. So watch out cause this could break things.</p>
<p>This code is run from alpha module's <code>.run</code> block.</p>
<h3>{{rollup}}</h3>
</div>
&#13;