2017-07-18 144 views
0

我在$routeProvider中创建了一个自定义键值对,当我尝试在我的控制器中访问该键时,它不工作并显示为未定义。下面是我的代码
TypeError:无法读取未定义在angularjs中的属性'mytext'

<!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在控制器不确定的,当我试图访问此?

回答

1

你可以使用时的决心funtion:

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

大号由于它的工作。但是有没有其他办法可以实现这一点。 – prudhvi259

相关问题