【发布时间】:2015-12-13 23:36:36
【问题描述】:
我是使用 ui-router 的新手,并且在延迟加载嵌套的 ui-view 时遇到了一些困难。我尝试了很多事情,虽然我想我已经接近了,但我不能让它工作,所以无论谁修复了下面分享的 plunker,都将获得正确答案。
-首先,require.js 引导主应用程序,index.html 包含两个 ui-views,一个用于导航,一个用于主要内容部分。主内容部分包含延迟加载(用oclazyload)的各种产品组合项目(PLNKR中的Test1)在选择一个时,在主要内容部分中。
-主应用模块在其配置方法中定义了各种状态,包括根据其ID和基于命名约定加载投资组合项的状态。
-当点击Test1时,它的主模块是懒加载的,这个模块定义了自己的状态,Test1有自己的index.html和自己的嵌套ui-view。值得注意的是,我还必须使用这个模块的 run 方法来运行一个在 $timeout 中包装 $state.go 的函数,以便在最初单击 Test1 时让模板内容出现在嵌套的 ui-view 中。这是骇人听闻的,无疑不是正确的方法,也可能是问题的根源,我们很快就会看到。我还尝试将 $state.go 放入服务中,但没有任何作用,因为我最终遇到了同样的问题。
-最后,事情在这里破裂了。如果从 Test1 内部单击主导航中的 Home,然后再次尝试单击 Test1,则之前出现在嵌套 ui-view 中的模板内容不会出现(显然,因为模块的 run 函数只运行一次)。手动点击重新加载状态的链接很容易让它重新出现,但显然这是不可取的。
TL/DR -- 主页 -> 点击 Test1 -> 工作! -> 点击 Home -> 点击 Test1 -> Breaks!
主应用模块和状态:
(function() {
angular.module('myApp', [
'ui.router',
//'door3.css',
'oc.lazyLoad'
])
.config(function($ocLazyLoadProvider, $stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('root', {
url: '/',
views: {
'nav': {
templateUrl: 'views/static/nav.html'
},
'content': {
templateUrl: 'views/portfolio.html'
}
}
})
.state('root.home', {
url: 'home',
views: {
'content@': {
templateUrl: 'views/portfolio.html'
}
}
})
.state('root.about', {
url: 'about',
views: {
'content@': {
templateUrl: 'views/about.html'
}
}
})
.state('root.portfolio', {
url: ':id',
views: {
'content@': {
// css: function($stateParams) {
// return '/portfolio/' + $stateParams.id + '/css/master.css';
// },
templateUrl: function($stateParams) {
return 'portfolio/' + $stateParams.id + '/index.html';
},
resolve: {
load: function($stateParams, $ocLazyLoad) {
return $ocLazyLoad.load({
files: ['portfolio/' + $stateParams.id + '/js/mainModule.js']
});
}
}
}
}
});
});
})();
懒加载Test1主模块和状态:
(function() {
angular.module('testingApp', [{
files: [
'portfolio/testing/controllers/testingCtrl.js'
]
}])
.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('root.portfolio.testing', {
url: '/',
views: {
'testingContent@root.portfolio': {
templateUrl: 'portfolio/testing/views/testfile.html',
controller: 'testingCtrl',
controllerAs: 'test'
}
}
})
})
.run(function($state, $timeout) {
$timeout(function() {
$state.go('root.portfolio.testing');
}, 0);
});
})();
【问题讨论】:
-
我在 UI-Router Extras 中编写了 Future States 来管理延迟加载 ui-router 状态的大部分陷阱:christopherthielen.github.io/ui-router-extras/#/future
标签: javascript angularjs angular-ui-router