angular.js - angular TypeError: Cannot read property 'id' of undefined?

查看:91
本文介绍了angular.js - angular TypeError: Cannot read property 'id' of undefined?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

demo
功能描述:
在一个页面中实现学生信息浏览的功能。首先,以列表的方式显示全部学生的姓名;然后,当在列表单击某个学生姓名时,进入改学生的详细资料页。显示该学生的全部资料。
5-7.html

<!DOCTYPE html>
<html lang="en" ng-app="a5_7">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="../bower_components/angular/angular.min.js"></script>
    <script type="text/javascript" src="../bower_components/angular-route/angular-route.min.js"></script>
    <style>
        body{
            font-size:13px;
        }
        .show{
            background-color:#cccccc;
            padding:8px;
            width:260px;
            margin:10px 0;
        }
    </style>
</head>
<body>
 <h1>浏览学生信息的主页</h1>
<div ng-view></div>
</body>
<script type="text/javascript">
var a5_7 = angular.module('a5_7',['ngRoute']);
    a5_7.controller('c5_7_1',['$scope', function($scope){
        $scope.students = students;

    }]);
    a5_7.controller('c5_7_2',['$scope', function($scope,$routeParams){
        for(var i=0; i<students.length; i++){
//            console.log(students.student[i]);
            if(students[i].stuId == $routeParams.id){

                $scope.student = students[i];
                break;
            }
        }
    }]);
    a5_7.config(['$routeProvider', function($routeProvider){
        $routeProvider.when('/',{
            controller:'c5_7_1',
            templateUrl:'5-7-1.html'
        }).when('/view/:id',{
            controller:'c5_7_2',
            templateUrl:'5-7-2.html',
            publicAccess:true
        }).otherwise({
            redirectTo:'/'
        });
    }]);

    var students = [
        { stuId:1000, name:'张明明',sex:'女',score:60},
        { stuId:1001, name:'李清思',sex:'女',score:80},
        { stuId:1002, name:'刘小华',sex:'男',score:90},
        { stuId:1003, name:'陈总总',sex:'男',score:70}
    ]
</script>
</html>

5-7-1.html

<div ng-repeat="stu in students" class="show">
    <a href="#view/:id">{{stu.name}}</a>
</div>

5-7-2.html

<div class="show">
    <div>学号:{{student.stuId}}</div>
    <div>姓名:{{student.name}}</div>
    <div>性别:{{student.sex}}</div>
    <div>分数:{{student.score}}</div>
</div>

操作步骤:
1.先打开5-7.html
2.点击学生姓名

3.控制台报错:

这是什么原因导致的,会是这句的问题吗?href="#view/:id"

解决方案

 a5_7.controller('c5_7_2',['$scope', function($scope,$routeParams){//没有注入$routeParams

请更改为

 a5_7.controller('c5_7_2',['$scope','$routeParams', function($scope,$routeParams){

这篇关于angular.js - angular TypeError: Cannot read property &#039;id&#039; of undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆