我想通过在angularjs中通过路由传递学生ID来显示学生详细信息。但是我做不到

时间:2019-04-24 05:39:37

标签: angularjs routing

我是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.

2 个答案:

答案 0 :(得分:0)

您好,Akansha用于通过url中的路由传递参数,您需要通过以下方式更改$ routeProvider:

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

这意味着,如果您的网址是/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 the ControllerHow to get the url parameters using AngularJS

中进行了描述

答案 1 :(得分:0)

在您的app.js路由配置代码中,添加如下所示的路由参数ID

       when('/show/:id', {
            templateUrl: 'show_student.html',
            controller: 'showCtrl'
        })

在您的index.html中,通过a标签传递ID

         <ul>
            <li><a href="#add"> Add Student </a></li>
            <li><a href="#show/{{id}}"> Show Student </a></li>
        </ul>

然后在show controller中,首先注入$routeParams

myApp.controller('showCtrl', function ($scope,$routeParams) {
  $scope.studentID = $routeParams.id; //passsed ID
 $scope.message = 'This is Show Student screen';
})
//you can use student ID to  filter your data in showStudent.html