2017-07-18 130 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

相關問題