要訪問$ route.current.params你當然需要包括由包括加載ngRoute模塊附加角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 onLoad的調用的current.params。
請參閱下面的代碼和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>
你在做什麼$ routeParams.bar? –
未定義,我認爲是因爲我在url欄中輸入url而沒有觸發角度。 – vzhen
如果我直接在視圖中使用'{{$ route.current.params.bar}}',那麼它就可以工作。 – vzhen