2017-07-18 4 views
0

J'ai créé une paire clé-valeur personnalisée dans $routeProvider et lorsque j'ai essayé cette clé pour accéder à mon contrôleur, elle ne fonctionne pas et s'affiche comme non définie. Ci-dessous mon code
TypeError: Impossible de lire la propriété 'mytext' de undefined dans angularjs

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

et mon Angular2.html est

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

Pourquoi montre mytext dans le contrôleur comme non défini quand j'ai essayé pour y accéder.?

Répondre

1

Vous pouvez utiliser le funtion résoudre quand:

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; 
    }); 
+0

L Merci cela a fonctionné. mais y a-t-il un autre moyen d'y parvenir? – prudhvi259