今天学习AngularJS,学到了一种传递参数的方法,做个笔记。
angular中使用routeParams传递参数.
在js的config中写入:
.when('/list/:id', {
templateUrl: 'views.route.detail.html',
controller: 'RouteDetailCtl'
})
在controller中直接使用:
.controller('RouteDetailCtl',function($scope, $routeParams) {
$scope.id = $routeParams.id;
})
就可以获得id的值。
具体代码如下。
HTML片段:
<body ng-app="ngRouteExample" class="ng-scope">
<script type="text/ng-template" id="views.route.detail.html">
<h1> about</h1>
<span style="color:#ff6666;"><h1>{{id}}</h1></span>
</script>
<script type="text/ng-template" id="embedded.home.html">
<h1> Home </h1>
</script>
<script type="text/ng-template" id="embedded.about.html">
<h1> About </h1>
<span style="color:#ff6666;"><li ng-repeat="id in ID">
<a href="#/list/{{ id }}"> ID{{ id }}</a>
</li></span>
</script>
<div>
<div id="navigation">
<a href="#/home">Home</a>
<a href="#/about">About</a>
</div>
<div ng-view="">
</div>
</div>
</body>
<script type="text/javascript">
angular.module('ngRouteExample', ['ngRoute'])
.controller('HomeController', function ($scope, $route) { $scope.$route = $route;})
.controller('AboutController', function ($scope, $route) { $scope.$route = $route;$scope.ID = [1,2,3];})
<span style="color:#ff6666;">.controller('RouteDetailCtl',function($scope, $routeParams) {
$scope.id = $routeParams.id;
})</span>
.config(function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'embedded.home.html',
controller: 'HomeController'
}).
when('/about', {
templateUrl: 'embedded.about.html',
controller: 'AboutController'
}).
<span style="color:#ff6666;">when('/list/:id', {
templateUrl: 'views.route.detail.html',
controller: 'RouteDetailCtl'
}).</span>
otherwise({
redirectTo: '/home'
});
});
</script>