要访问 $route.current.params 你当然需要包含 ngRoute 模块,该模块是通过包含额外的 angular-route.js 来加载的
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular-route.js"></script>
您可以通过创建 init() 函数或使用 routeChangeSuccess 访问 current.params onLoad。
请参阅下面的代码和jsfiddle上的工作示例。
<script type="text/javascript">
var app = angular.module( "myApp", ['ngRoute'] );
app.config( function ( $routeProvider ) {
$routeProvider
.when( '/foo/:bar', {
controller: 'MainCtrl',
templateUrl: 'template.html' }
);
});
app.controller('MainCtrl', [
'$rootScope', '$scope', '$route', '$routeParams', function($rootScope, $scope, $route, $routeParams){
$scope.routeParams = {};
$scope.routeParams.bar = $routeParams.bar;
var init = function () {
$scope.initCurrentParams = {};
$scope.$route = $route;
$scope.initCurrentParams.bar = $scope.$route.current.params.bar;
console.log('from init', $scope.initCurrentParams.bar);
};
init();
$scope.$on('$routeChangeSuccess', function() {
$scope.routeChangeSuccessCurrentParams = {};
$scope.$route = $route;
$scope.routeChangeSuccessCurrentParams.bar = $scope.$route.current.params.bar;
console.log('from routeChangeSuccess', $scope.routeChangeSuccessCurrentParams.bar);
});
}]);
</script>
<div ng-app="myApp" class="ng-scope">
<script type="text/ng-template" id="template.html">
$routeParams.bar: {{ routeParams.bar }} <br />
initCurrentParams.bar: {{ initCurrentParams.bar }} <br />
routeChangeSuccessCurrentParams.bar: {{ routeChangeSuccessCurrentParams.bar }} <br />
</script>
<div class="ng-scope">
<ul>
<li><a href="#/foo/1">bar 1</a></li>
</ul>
<ng-view></ng-view>
</div>
</div>