TypeError: Cannot read property 'mytext' of undefined in angularjs

TypeError: Cannot read property 'mytext' of undefined in angularjs

我在 $routeProvider 中创建了一个自定义键值对,当我尝试在我的控制器中访问此键时,它不起作用并显示为未定义。下面是我的代码

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body ng-controller="AngularCtrl">

<h2>Routes with params</h2>
    <table class="table table-striped">
        <thead>
            <th>
                <td>#</td>
                <td>Topic</td>
                <td>Desc</td>
            </th>
        </thead>
            <tr>
                <td>1</td>
                <td>Controller</td>
                <td><a href="#Angular/1">Topic Details</a></td>
            </tr>
            <tr>
                <td>2</td>
                <td>Models</td>
                <td><a href="#Angular/2">Topic Details</a></td>
            </tr>
            <tr>
                <td>3</td>
                <td>Views</td>
                <td><a href="#Angular/3">Topic Details</a></td>
            </tr>
    </table>

    <div ng-view></div>
</body>
    <script type="text/javascript">
        var app = angular.module("myApp", ["ngRoute"]);

        app.config(function($routeProvider){
            $routeProvider
            .when('/Angular/:topicId', {
                mytext: "This is Angular",
                templateUrl: 'Angular2.html',
                controller: 'AngularCtrl'
            });
        });

        app.controller('AngularCtrl', function($scope, $routeParams, $route){
            $scope.tutorialid = $routeParams.topicId;
            $scope.text = $route.current.mytext;
        });
    </script>
</html>

我的 Angular2.html 是

<h2>Angular</h2>
<br>
{{text}}
<br/>
{{tutorialid}}

为什么当我尝试访问它时,控制器中的 mytext 显示为未定义。?

你可以使用 when:

的解析函数
app.config(function($routeProvider){
        $routeProvider
        .when('/Angular/:topicId', {
            templateUrl: 'Angular2.html',
            controller: 'AngularCtrl',
            resolve: {
                mytext: function($route){$route.current.params.mytext= 'This is Angular'}
            }
        });
    });

    app.controller('AngularCtrl', function($scope, $routeParams, $route){
        $scope.tutorialid = $routeParams.topicId;
        $scope.text = $routeParams.mytext;
    });