所以这是我的代码的想法:
.factory('foo', function(CONFIG){
var bar = //value returned from config's resolve function
}
这是.config:
.config(function($routeProvider){
$routeProvider
.when(url, {
resolve:{
function(){
return value;
}
我如何将该值从resolve传递给.factory?
答案 0 :(得分:0)
.config(function($routeProvider){
$routeProvider
.when(url, {
resolve:{
CONFIG: function(){
return value;
},
ANOTHERTHINGTORESOLVE: function(){
return "somethingElseHere";
}
}
)
然后CONFIG和ANOTHERTHINGTORESOLVE可以作为依赖项传递
以下是scott allen的nice article演示
您可以将工厂传递给解决方案并在解决路径之前完成工作
resolve: {
CONFIG: function(someFactory){
return someFactory.doSomething(value);
}
}
答案 1 :(得分:0)
您只能在providers
阶段注入config
,而不是factories
。
如果对你没关系(为什么会这样?)这是人们可以做到的:
<小时/>
HTML模板
<!-- where ng-app="app" and ng-controller="Ctrl" -->
<body>
<div>
<a href="#/main">main</a><br>
</div>
<hr>
<div ng-view></div>
</body>
<强>的JavaScript 强>
angular.module('app', ['ngRoute'])
.provider('foo', function fooProvider() {
var bar = 'bar';
this.setBar = function(val) {
bar = val;
};
this.$get = function() {
var foo = {};
foo.getBar = function() {
return bar;
};
return foo;
};
})
.config(function($routeProvider, fooProvider) {
$routeProvider
.when('/main', {
template: '<div>foo: {{ foo }}</div>',
controller: 'Ctrl',
resolve: fooProvider.setBar('set from main route')
});
})
.controller('Ctrl', function($scope, foo) {
$scope.foo = foo.getBar();
});