一、AngularJS动态加载控制器和视图实例
路由配置关键代码:
- //二级页面
- $stateProvider.state('main', {
- url: '/:name',
- /**如果需要动态加载数据和控制器***/
- views: {
- "": {
- templateUrl: function ($stateParams) {
- console.info($stateParams);
- return '/template/' + $stateParams.name + '.html';
- },
- resolve: {
- des: function ($ocLazyLoad, $stateParams) {
- if ($stateParams.name == 'about')
- return;
- return $ocLazyLoad.load('/scripts/myjs/' + $stateParams.name + '.js');
- }
- }
- }
- }
- });
1.引用:
- <script src="../Scripts/jquery-1.10.2.min.js"></script>
- <script src="../Scripts/Angular/angular.min.js"></script>
- <script src="../Scripts/Angular/ocLazyLoad.min.js"></script>
- <script src="../Scripts/Angular/angular-ui-router.min.js"></script>
- <link href="../Content/bootstrap.min.css" rel="stylesheet" />
2.HTML
- <div class="container" ng-app="myApp">
- <ul class="nav nav-pills">
- <li role="presentation"><a href="#/home">首页</a></li>
- <li role="presentation"><a href="#/about">关于页面</a></li>
- </ul>
- <div class="panel panel-danger">
- <div class="panel-heading">
- <div class="panel-title">模板内容</div>
- </div>
- <div class="panel-body" ui-view></div>
- </div>
- </div>
3.Js
- var app = angular.module('myApp', ['oc.lazyLoad', 'ui.router']);
- //配置路由
- app.config(function ($stateProvider, $urlRouterProvider) {
- $urlRouterProvider
- .when('', '/');
- //首页
- $stateProvider.state('index', {
- url: '/',
- templateProvider: function ($stateParams) {
- console.info('这是首页');
- return '<h1>这是首页</h1>';
- }
- });
- //二级页面
- $stateProvider.state('main', {
- url: '/:name',
- /***如果只是动态加载视图**/
- //templateUrl: function ($stateParams) {
- // console.info($stateParams);
- // return '/template/' + $stateParams.name + '.html';
- //},
- //controller: 'homeController',
- /**如果需要动态加载数据和控制器***/
- views: {
- "": {
- templateUrl: function ($stateParams) {
- console.info($stateParams);
- return '/template/' + $stateParams.name + '.html';
- },
- resolve: {
- des: function ($ocLazyLoad, $stateParams) {
- if ($stateParams.name == 'about')
- return;
- return $ocLazyLoad.load('/scripts/myjs/' + $stateParams.name + '.js');
- }
- }
- }
- }
- });
- });
- 本文转自黄聪博客园博客,原文链接:http://www.cnblogs.com/huangcong/p/6771532.html,如需转载请自行联系原作者