首页 > 解决方案 > 我想通过 angularjs 中的路由传递学生 ID 来显示学生详细信息。但我做不到

问题描述

我是 Angular JS 的新手,并尝试通过使用路由传递学生 ID 来查看学生详细信息

我已经编写了一些代码,但不知道在哪里添加学生的详细信息以及如何传递学生 ID

this is the code for index.html

<div>
    <div>
        <div>
            <ul>
                <li><a href="#add"> Add Student </a></li>
                <li><a href="#show"> Show Student </a></li>
            </ul>
        </div>
        <div >
            <div ng-view></div>
        </div>
    </div>
</div>   

this is the code for app.js
```````````````````````````````````````````
var myApp = angular.module('stuApp', []);
myApp.config(['$routeProvider',
    function ($routeProvider) {
        $routeProvider.
            when('/add', {
                templateUrl: 'add_student.html',
                controller: 'addCtrl'
            }).
            when('/show', {
                templateUrl: 'show_student.html',
                controller: 'showCtrl'
            }).
            otherwise({
                redirectTo: '/add'
            });
    }]);


myApp.controller('addCtrl', function ($scope) {

    $scope.message = 'This is Add new Student screen';

});


myApp.controller('showCtrl', function ($scope) {

    $scope.message = 'This is Show Student screen';

})

我想通过表单添加学生详细信息,但不知道如何在控制器中添加这些值

add_student.html
````````````````````````````
<script type="text/ng-template" id="add_student.html">
<h2>Add New Student</h2>

{{ message }}
</script>

show_student.html

<script type="text/ng-template" id="show_student.html">
<h2>Show Order</h2>

{{ message }}
</script>

I want the output as to pass object in controller display the students name and by clicking on the name student details should be displayed.

标签: angularjsrouting

解决方案


嗨,Akansha,通过 url 中的路由传递参数,您需要更改 $routeProvider,如下所示:

when('/add/:StudentId', {
            templateUrl: 'add_student.html',
            controller: 'addCtrl'
        })

这意味着如果您的 url 是/add/1837参数 StudentId 将具有值 1837。

要在控制器中获取 StudenId 的值,您可以使用 $routeParams。
因此,例如,您的控制器可能如下所示:

 myApp.controller('showCtrl', function ($scope, $routeParams) {
    $scope.message = 'This is Show Student screen';
    var studentId = $routeParams.StudentId;
 })

您可以从以下链接获取更多信息URL-Routing - GitHub
还有其他访问 url 参数的方法,它们在以下 SO 问题Access URL parameters in Angularjs in ControllerHow to get the url parameters using AngularJS 中进行了描述


推荐阅读