K. *_* D. 38 javascript angularjs
我有多个路由调用相同的控制器,我想传递不同的变量.
// Example
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed 'exampleA'
}).
when('/b', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed 'exampleB'
});
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用"resolve"对象:
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController',
resolve: {test: function() { return true; }}
});
Run Code Online (Sandbox Code Playgroud)
要将值作为依赖项传递:
app.controller('MyController', ['$scope', 'test', function ($scope, test) {
console.log(test); // true
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我的应用程序崩溃,如果在其他路由上缺少resolve对象,我想传递可选参数.
有没有办法将特定参数传递给Controller(来自路由提供商)?
谢谢
Aid*_*din 57
路由:
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController',
paramExample: 'exampleA'
}).
when('/b', {
templateUrl: 'test.html',
controller: 'MyController',
paramExample: 'exampleB'
});
Run Code Online (Sandbox Code Playgroud)
访问:在您的控制器中注入$ route然后使用它
app.controller('MyController', ['$scope', '$route', function ($scope, $route) {
var paramValue = $route.current.$$route.paramExample;
console.log(paramValue);
}
Run Code Online (Sandbox Code Playgroud)
Way*_*ery 13
您可以使用resolve并$route.currrent.params.test
传递参数,如下所示:
$routeProvider
.when('/a', {
templateUrl: 'view.html',
controller: 'MainCtrl',
resolve: {
test: function ($route) { $route.current.params.test = true; }
}
})
.when('/b', {
templateUrl: 'view.html',
controller: 'MainCtrl',
resolve: {
test: function ($route) { $route.current.params.test = false; }
}
})
Run Code Online (Sandbox Code Playgroud)
然后在您的控制器中,您可以从$ routeParams访问它:
app.controller('MainCtrl', function($scope, $routeParams) {
$scope.test = $routeParams.test;
})
Run Code Online (Sandbox Code Playgroud)
http://plnkr.co/edit/ct1ZUI9DNqSZ7S9OZJdO?p=preview
归档时间: |
|
查看次数: |
42313 次 |
最近记录: |