2014-12-03 102 views
0

我需要一种动态加载视图和相关控制器的方法。 我的APP将包含许多视图和许多控制器。 我不想加载应用程序设置上的所有控制器定义,但我想加载一个视图和动态管理视图的控制器。Angular JS ui-router - 加载动态视图和动态控制器

例如:

/*index.html*/ 

<body> 
    <div ui-view></div> 
    <a ui-sref="state1">State 1</a> 
    <a ui-sref="state2">State 2</a> 
</body> 

/*<!-- partials/state1.html -->*/ 

<script>/* controller definition */</script> 
<div ng-controller="Cont"> 
/* content of view */ 
</div> 

/*app.js*/ 
var myApp = angular.module('myApp', ['ui.router']); 

myApp.config(function($stateProvider, $urlRouterProvider) { 
    $stateProvider 
    .state('state1', { 
     url: "/state1", 
     templateUrl: "partials/state1.html" 
    }); 
}); 

OR

/*index.html*/ 

<body> 
    <div ui-view></div> 
    <a ui-sref="state1">State 1</a> 
    <a ui-sref="state2">State 2</a> 
</body> 

/*<!-- partials/state1.html -->*/ 

<div ng-controller="Cont"> 
/* content of view */ 
</div> 

/*app.js*/ 
var myApp = angular.module('myApp', ['ui.router']); 

myApp.config(function($stateProvider, $urlRouterProvider) { 
    $stateProvider 
    .state('state1', { 
     url: "/state1", 
     templateUrl: "partials/state1.html", 
     controller: /*Load the controller of state1 view*/ 
    }); 
}); 

当我加载我要加载的相对控制器STATE1视图。

+0

你问你是否可以在路由定义中使用'controller:/ * load ... * /'来加载控制器? – 2014-12-03 19:27:22

回答

0

您可以使用ocLazyLoad延迟加载控制器,css等。还有另外一个库,但是我坚持使用ocLazyLoad,因为它的大小,功能以及我不使用requirejs。如果您只需要加载js,请查看$script.js。这是令人难以置信的小。