javascriptangularjsroute-provider

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


i created a custom key-value pair in $routeProvider and when i tried this key to access in my controller it is not working and showing as undefined. Below is my code

<!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>

and my Angular2.html is

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

Why it is showing mytext in controller as undefined when i tried to access this.?


Solution

  • You could use the resolve funtion of 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;
        });