angular的resovle机制,实际上是应用了promise,在进入特定的路由之前给我们一个做预处理的机会
1、在进入这个路由之前先懒加载对应的 .js
$stateProvider
.state('owner_detail_room',{
url: '/owner_detail_room/{id:[0-9]{1,10}}',
views:{
'main' : {
templateUrl:function() { return 'templates/owner_detail_room.html'},
controller: 'owner_detail_roomCtrl'
}
},
resolve:{
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad){
return $ocLazyLoad.load('js/owner_detail_roomCtrl.js')
}]
}
})
2、请注意,resolve是一个对象,它的key由我们自己指定,value则是一个promise的异步请求或字符串
首先,来一个多个键值对的例子1-懒加载js,2-获取user,3-判断页面权限
.state('owner_detail_room',{
url: '/owner_detail_room/{id:[0-9]{1,10}}',
views:{
'main' : {
templateUrl:function() { return 'templates/owner_detail_room.html'},
controller: 'owner_detail_roomCtrl'
}
},
resolve:{
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad){
return $ocLazyLoad.load('js/owner_detail_roomCtrl.js')
}],
user: ['userservice',function(userservice){
return userservice.getUser();
}],
userLevelCheck:['LevelCheck','userservice',function(LevelCheck,userservice){
var isPass = LevelCheck.check(userservice.userLevel);
if(isPass){
return userservice.userLevel;
}else{
$state.go('level-is-not-enough');
}
}]
}
})
然后在对应的页面的ctrl中,可以注入resolve中的返回
app.controller('owner_detail_roomCtrl',['$scope','user', function($scope,users) {
$scope.users = users;
});
3、从resolve到进入路由Ctrl中,应用到的就是promise,($q服务属性方法:$q.defer(), $q.all(), $q.when(), $q.reject(), $q.resolve().....)
来个栗子,剩下看大家了,
resolve: {
data: function(User, Post, $q) {
deferred = $q.defer(); $q.all([User.getAll, Post.getTops()]).then(function(results) {
deferred.resolve({
users: results[0],
posts: results[1]
})
}); return deferred.promise;
}
}
最后的最后,如果有错误,请务必,一定要指出