Javascript AngularJS - 如何使用 $routeParams 生成 templateUrl?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11534710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS - How to use $routeParams in generating the templateUrl?
提问by dnc253
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:
我们的应用程序有 2 级导航。我们想使用 AngularJS$routeProvider
动态地为<ng-view />
. 我正在考虑做一些类似的事情:
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?
我只是不知道如何填充<<>>
. 我知道primaryNav 和secondaryNav 绑定到$routeParams,但是如何在此处访问$routeParams 以动态提供模板?
采纳答案by Gloopy
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:
我找不到注入和使用$routeParams
服务的方法(我认为这是一个更好的解决方案)我试过这个认为它可能有效:
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:
这产生了这个错误:
Unknown provider: $routeParams from myApp
未知提供者:来自 myApp 的 $routeParams
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:
如果这样的事情是不可能的,您可以将您templateUrl
的指向一个部分 HTML 文件,ng-include
然后使用$routeParam
s在您的控制器中设置 URL,如下所示:
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
以此作为你的 urlRouter.html
<div ng-include src="templateUrl"></div>
回答by jlareau
This very helpful feature is now available starting at version 1.1.2 of AngularJS. It's considered unstable but I have used it (1.1.3) and it works fine.
这个非常有用的功能现在从 AngularJS 1.1.2 版本开始可用。它被认为是不稳定的,但我已经使用了它(1.1.3)并且它工作正常。
Basically you can use a function to generate a templateUrl string. The function is passed the route parameters that you can use to build and return the templateUrl string.
基本上你可以使用一个函数来生成一个 templateUrl 字符串。该函数传递了可用于构建和返回 templateUrl 字符串的路由参数。
var app = angular.module('app',[]);
app.config(
function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/home'}).
when('/users/:user_id',
{
controller:UserView,
templateUrl: function(params){ return '/users/view/' + params.user_id; }
}
).
otherwise({redirectTo:'/'});
}
);
Many thanks to https://github.com/lrlopezfor the pull request.
非常感谢https://github.com/lrlopez的拉取请求。
回答by Ravi K.
templateUrl can be use as function with returning generated URL. We can manipulate url with passing argument which takes routeParams.
templateUrl 可以用作返回生成的 URL 的函数。我们可以使用带有 routeParams 的传递参数来操作 url。
See the example.
请参阅示例。
.when('/:screenName/list',{
templateUrl: function(params){
return params.screenName +'/listUI'
}
})
Hope this help.
希望这有帮助。
回答by Cody
Alright, think I got it...
好吧,我想我明白了......
Little background first: The reason I needed this was to stick Angular on top of Node Express and have Jade process my partials for me.
首先是一点背景知识:我需要它的原因是将 Angular 放在 Node Express 之上,并让 Jade 为我处理我的部分。
So here's whatchya gotta do... (drink beer and spend 20+ hours on it first!!!)...
所以这是你必须做的事情......(喝啤酒,然后先花 20 多个小时!!!)......
When you set up your module, save the $routeProvider
globally:
设置模块时,$routeProvider
全局保存:
// app.js:
var routeProvider
, app = angular.module('Isomorph', ['ngResource']).config(function($routeProvider){
routeProvider = $routeProvider;
$routeProvider
.when('/', {templateUrl: '/login', controller: 'AppCtrl'})
.when('/home', {templateUrl: '/', controller: 'AppCtrl'})
.when('/login', {templateUrl: '/login', controller: 'AppCtrl'})
.when('/SAMPLE', {templateUrl: '/SAMPLE', controller: 'SAMPLECtrl'})
.when('/map', {templateUrl: '/map', controller: 'MapCtrl'})
.when('/chat', {templateUrl: '/chat', controller: 'ChatCtrl'})
.when('/blog', {templateUrl: '/blog', controller: 'BlogCtrl'})
.when('/files', {templateUrl: '/files', controller: 'FilesCtrl'})
.when('/tasks', {templateUrl: '/tasks', controller: 'TasksCtrl'})
.when('/tasks/new', {templateUrl: '/tasks/new', controller: 'NewTaskCtrl'})
.when('/tasks/:id', {templateUrl: '/tasks', controller: 'ViewTaskCtrl'})
.when('/tasks/:id/edit', {templateUrl: '/tasks', controller: 'EditTaskCtrl'})
.when('/tasks/:id/delete', {templateUrl: '/tasks', controller: 'DeleteTaskCtrl'})
.otherwise({redirectTo: '/login'});
});
// ctrls.js
...
app.controller('EditTaskCtrl', function($scope, $routeParams, $location, $http){
var idParam = $routeParams.id;
routeProvider.when('/tasks/:id/edit/', {templateUrl: '/tasks/' + idParam + '/edit'});
$location.path('/tasks/' + idParam + '/edit/');
});
...
That may be more info than what was needed...
这可能比需要的信息更多......
Basically, you'll wanna store your Module's
$routeProvider
var globally, eg asrouteProvider
so that it can be accessed by your Controllers.Then you can just use
routeProvider
and create a NEW route (you can't 'RESET a route' / 'REpromise'; you must create a new one), I just added a slash (/) at the end so that it is as semantic as the first.Then (inside your Controller), set the
templateUrl
to the view you want to hit.Take out the
controller
property of the.when()
object, lest you get an infinite request loop.And finally (still inside the Controller), use
$location.path()
to redirect to the route that was just created.
基本上,您需要
$routeProvider
全局存储模块的var,例如,routeProvider
以便您的控制器可以访问它。然后你就可以使用
routeProvider
并创建一个新的路由(你不能“重置路由”/“重新承诺”;你必须创建一个新路由),我只是在最后添加了一个斜杠(/),以便它是语义作为第一。然后(在您的控制器中),将 设置为
templateUrl
您想要点击的视图。取出对象的
controller
属性.when()
,以免陷入无限请求循环。最后(仍在控制器中),用于
$location.path()
重定向到刚刚创建的路由。
If you're interested in how to slap an Angular app onto an Express app, you can fork my repo here: https://github.com/cScarlson/isomorph.
如果您对如何将 Angular 应用程序贴在 Express 应用程序上感兴趣,您可以在这里 fork 我的 repo:https: //github.com/cScarlson/isomorph。
And this method also allows for you to keep the AngularJS Bidirectional Data-Bindings in case you want to bind your HTML to your database using WebSockets: otherwise without this method, your Angular data-bindings will just output {{model.param}}
.
并且此方法还允许您保留 AngularJS 双向数据绑定,以防您想使用 WebSockets 将 HTML 绑定到数据库:否则,如果没有此方法,您的 Angular 数据绑定将只输出{{model.param}}
.
If you clone this at this time, you'll need mongoDB on your machine to run it.
如果你此时克隆它,你需要在你的机器上安装 mongoDB 来运行它。
Hope this solves this issue!
希望这能解决这个问题!
Cody
科迪
Don't drink your bathwater.
不要喝你的洗澡水。
回答by Jamie Pate
I've added support for this in my fork of angular. It allows you to specify
我在我的 angular 分支中添加了对此的支持。它允许您指定
$routeProvider
.when('/:some/:param/:filled/:url', {
templateUrl:'/:some/:param/:filled/template.ng.html'
});
https://github.com/jamie-pate/angular.js/commit/dc9be174af2f6e8d55b798209dfb9235f390b934
https://github.com/jamie-pate/angular.js/commit/dc9be174af2f6e8d55b798209dfb9235f390b934
not sure this will get picked up as it is kind of against the grain for angular, but it is useful to me
不确定这是否会被接受,因为它有点违反角度,但对我很有用
回答by Ron deBoer
Router:-
路由器:-
...
.when('/enquiry/:page', {
template: '<div ng-include src="templateUrl" onload="onLoad()"></div>',
controller: 'enquiryCtrl'
})
...
Controller:-
控制器:-
...
// template onload event
$scope.onLoad = function() {
console.log('onLoad()');
f_tcalInit(); // or other onload stuff
}
// initialize
$scope.templateUrl = 'ci_index.php/adminctrl/enquiry/'+$routeParams.page;
...
I believe it is a weakness in angularjs that $routeParams is NOT visible inside the router. A tiny enhancement would make a world of difference during implementation.
我认为 $routeParams 在路由器内部不可见是 angularjs 的一个弱点。在实施过程中,微小的增强将带来天壤之别。
回答by Aniket Jha
//module dependent on ngRoute
var app=angular.module("myApp",['ngRoute']);
//spa-Route Config file
app.config(function($routeProvider,$locationProvider){
$locationProvider.hashPrefix('');
$routeProvider
.when('/',{template:'HOME'})
.when('/about/:paramOne/:paramTwo',{template:'ABOUT',controller:'aboutCtrl'})
.otherwise({template:'Not Found'});
}
//aboutUs controller
app.controller('aboutCtrl',function($routeParams){
$scope.paramOnePrint=$routeParams.paramOne;
$scope.paramTwoPrint=$routeParams.paramTwo;
});
in index.html
在 index.html 中
<a ng-href="#/about/firstParam/secondParam">About</a>
firstParam and secondParam can be anything according to your needs.
firstParam 和 secondParam 可以是任何你需要的东西。
回答by mcneela86
I was having a similar issue and used $stateParams
instead of routeParam
我遇到了类似的问题并使用$stateParams
而不是routeParam