我的局部视图中有一个js文件。如果加载了部分,我将如何动态加载它?
我的目录结构是
应用
--- CSS
------的style.css
---- JS
------- app.js
------- appRotes.js
-------的script.js
----观点
------- home.html的
------- about.html
----的index.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<body ng-app="myapp">
<p><a href="#/">Main</a></p>
<a href="#about">Red</a>
<div ng-view></div>
<script src="js/app.js"></script>
<script src="js/appRoutes.js"></script>
</body>
</html>
我的 app.js
angular.module("myapp", ["myapp.routes"]);
我的 appRoutes.js
angular.module("myapp.routes",["ngRoute"]).
config(function($routeProvider, $locationProvider){
$routeProvider.
when("/",{
templateUrl : "views/home.html"
})
.otherwise({
redirectTo: '/'
})
.when("/b",{
templateUrl : "views/about.html"
})
.otherwise({
redirectTo: '/'
});
});
我的 about.html
<h1>About</h1>
<script src="script.js"></script>
答案 0 :(得分:0)
可以使用oclazyload
进行动态js文件加载
使用ngRoute
$routeProvider
.when('/time',
{
controller: 'timeController',
templateUrl: 'views/home.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load([{
name: 'myApp',
files: ['js/AppCtrl.js']
}]);
}]
}
})
使用ui router
$stateProvider.state('index', {
url: "/", // root route
views: {
"lazyLoadView": {
controller: 'AppCtrl', // This view will use AppCtrl loaded below in the resolve
templateUrl: 'views/home.html'
}
},
resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load('js/AppCtrl.js');
}]
}
});
您可以使用凉亭安装它
bower install oclazyload --save