因为发现resolve不仅仅是loaded时触发,在返回时也会触发,但是返回时controller获取到的没有更新。
这个例子里也是将resolve得到的东西放在service里去取的,本来想试着改成注入方式获取看看是不是也一样的情况,如果还是不行的话打算也放在service里或者resolve的数据只在loaded时使用。
所以想找个例子测试一下,但是老是注入失败。
这里是没注入test的 注入即报错
http://jsfiddle.net/abelmakihara/x99b2o2p/3/
高洛峰2017-05-15 17:04:13
That’s it. I looked at it carefully. There is something wrong with your understanding of ngRoute
. I changed it. Please take a look again: jsFiddle
The main difference is:
app.factory('rulesFactory', ['$q', '$timeout',
function($q, $timeout) {
return function() {
return $q(function(resolve){
$timeout(function() {
//这里如果期待返回值,就要用$q封装,并resolve
resolve('Change time in seconds:' + new Date().getTime() / 1000);
}, 1000)
});
};
}
]);
$routeProvider
.when('/', {
action: 'index',
resolve: {
//这里的resolve真对的是该路由自己的controller
'test': ['rulesFactory', function(rulesFactory) {
return rulesFactory();
}]
},
//所以一定要定义一个自己的AController
controller: 'AController',
template: '<h3>{{test}}</h3>'
})
.when('/page', {
action: 'page',
resolve: {
'test': ['rulesFactory', function(rulesFactory) {
return rulesFactory();
}]
},
controller: 'BController',
template: '<h3>{{test}}</h3>'
})
//然后,AController,BController就可以注入test了,并且test的值就是上面resolve的那堆字符串
app.controller('AController', ['$scope', 'test',
function($scope, test) {
$scope.test = test;
}
]);
app.controller('BController', ['$scope', 'test',
function($scope, test) {
$scope.test = test;
}
]);