问题描述
我们的应用程序有 2 级导航.我们想使用 AngularJS $routeProvider
动态地为 提供模板.我正在考虑做一些类似的事情:
angular.module('myApp', []).配置(['$routeProvider',函数($routeProvider){$routeProvider.when('/:primaryNav/:secondaryNav', {templateUrl: 'resources/angular/templates/nav/'+<>+'/'+<>+'.html'});}]);
我只是不知道如何填充 <<>>
中的部分.我知道primaryNav 和secondaryNav 绑定到$routeParams,但是我如何在此处访问$routeParams 以动态提供模板?
我找不到注入和使用 $routeParams
服务的方法(我认为这会是更好的解决方案)我试过这个,认为它可能有效:
angular.module('myApp', []).配置(功能($routeProvider,$routeParams){$routeProvider.when('/:primaryNav/:secondaryNav', {templateUrl: 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html'});});
产生此错误的原因:
未知提供者:来自 myApp 的 $routeParams
如果这样的事情是不可能的,你可以改变你的 templateUrl
以指向一个只有 ng-include
的部分 HTML 文件,然后在你的控制器使用 $routeParam
像这样:
angular.module('myApp', []).配置(功能($routeProvider){$routeProvider.when('/:primaryNav/:secondaryNav', {templateUrl: 'resources/angular/templates/nav/urlRouter.html',控制器:'路由控制器'});});功能 RouteController($scope, $routeParams) {$scope.templateUrl = 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html';}
以此作为您的 urlRouter.html
Our application has 2-level navigating. We want to use AngularJS $routeProvider
to dynamically provide templates to an <ng-view />
. I was thinking of doing something along the lines of this:
angular.module('myApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/:primaryNav/:secondaryNav', {
templateUrl: 'resources/angular/templates/nav/'+<<primaryNavHere>>+'/'+<<secondaryNavHere>>+'.html'
});
}]);
I just don't know how to populate the parts within the <<>>
. I know the primaryNav and secondaryNav get bound to the $routeParams, but how do I access $routeParams here in order to dynamically serve up the template?
I couldn't find a way to inject and use the $routeParams
service (which I would assume would be a better solution) I tried this thinking it might work:
angular.module('myApp', []).
config(function ($routeProvider, $routeParams) {
$routeProvider.when('/:primaryNav/:secondaryNav', {
templateUrl: 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html'
});
});
Which yielded this error:
If something like that isn't possible you can change your templateUrl
to point to a partial HTML file that just has ng-include
and then set the URL in your controller using $routeParam
s like this:
angular.module('myApp', []).
config(function ($routeProvider) {
$routeProvider.when('/:primaryNav/:secondaryNav', {
templateUrl: 'resources/angular/templates/nav/urlRouter.html',
controller: 'RouteController'
});
});
function RouteController($scope, $routeParams) {
$scope.templateUrl = 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html';
}
With this as your urlRouter.html
<div ng-include src="templateUrl"></div>
这篇关于AngularJS - 如何使用 $routeParams 生成 templateUrl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!