我正在尝试在 Angular 中进行基本路由。
我的配置看起来像
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
templateUrl: 'home.html', controller: 'loginCtrl'
},
$routeProvider.when('/user_profile/, {
templateUrl: 'user_profile.html', controller: 'UserProfileCtrl'
}
});
当我有一个指向 user_profile 的链接时,我无法获得 $route 参数。
<a href="user_profile/?user_id=9">Go To Profile</a>
在 Controller
$route.params
是 undefined
.我试着做一个 plnkr但显然我在这里遗漏了一些基本的东西
编辑:
$routeParams
我有一个从服务器获取用户信息的模块。当我通过
$routeParams
是否设置为这个。<script type="text/javascript">
angular.module('userFromServer', [])
.service('currentUser', function() {
<% if logged_in %>
this.name = '<%= @User.name %>';
this.id = '<%= @User.id %>'
<% else %>
this.name, this.id = '';
<% end %>
})
</script>
最佳答案
看看这个
您可以使用 $routeParams
用于获取路由参数
Plunker (Non HTML5 Mode)
Plunker (HTML5 Mode)
app = angular.module('MyApp', ['ngRoute']);
app.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'loginCtrl'
})
.when('/user_profile/:user_id', {
templateUrl: 'user_profile.html',
controller: 'UserProfileCtrl'
});
});
app.controller('loginCtrl', function($scope, $routeParams) {
$scope.name = "Hello"
console.log($routeParams);
});
app.controller('UserProfileCtrl', function($scope, $routeParams) {
$scope.name = "UserProfile"
console.log($routeParams);
});
关于angularjs - $route.current 在尝试获取当前参数时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29652431/