2017-09-05 137 views
0
....   

.state('books', { 
      url: '/book/chapter/:chap', 
      templateUrl: "views/chapter.html", 
      params: { chap: .........} 
     }) 

嗨! 我在特定的控制器中有一個變量,我想將它的值傳遞給路由參數。最終,我想更改該變量的值,以便可以使用此相同的路線創建新的網址。將來自控制器的變量傳遞給路由參數

我正在使用ui-router,因爲您可能已經注意到了。

我也很好奇你將如何解決以下問題: 基本上我想打開一本書的特定章節,讓我們說第5章。然後,我想在頁面左側顯示鏈接每個剩餘的章節,這就是爲什麼我想改變變量的值。你如何使用ng-repeat解決這個問題? 我正在考慮使用getArticle(如下所示)獲取章節號,然後用ng-repeat重複其餘章節?想法?

angular 
    .module('BookLibrary') 
    .controller("ChapterController", ["$scope","stateParams", "ChapterControllerService", function($scope, $stateParams, ChapterControllerService){ 

     $scope.chapterList = ChapterControllerService.chapters; 
     $scope.getArticle = chapterList[0].chapter; 

    }]); 

chapterList看起來是這樣的:

chapterList = [ 
     { 
      chapter: "1", 
      content: "Chapter 1 goes here" 
     }, 
     { 
      chapter: "2", 
      content: "Chapter 2 goes here" 
     }, 
     { 
      chapter: "3", 
      content: "Chapter 3 goes here" 
     } 
    ]; 
+0

怎麼可能,我們知道?你沒有告訴我們什麼是$ scope.chapterList,也不是$ scope.getArticle。不知道你的模型,我們不能告訴你如何使用它。 –

+0

@JBNizet我的壞,那裏是:) –

+0

所以,你需要'{{ c.content }}'。您需要將$ scope.remainingChapters設置爲從下一章開始的子數組。你有什麼嘗試?具體問題是什麼?爲什麼你使用字符串而不是數字作爲章節號? –

回答

0

有多種問題,所以在這裏開始你的狀態參數。在狀態參數中,您可以像這樣在狀態中聲明params的默認值。

.state('books', { 
     url: '/book/chapter/:chap', 
     templateUrl: "views/chapter.html", 
     params: { chap: null} 
    }) 

這將默認值爲null。也許你總是想默認第1章?如果是這種情況,您可以使用params: {chap: '1'}(因爲您正在使用字符串)。 要將值傳遞給狀態,有多種方法可以實現。假設您正在使用ui-sref,則可以在鏈接中正確輸入參數值。

ui-sref="books({ chap: 3 })" 

但是,您想要使用ng-repeat的對象的鏈接列表。所以,你可以做這樣的事情

<ul>  
    <li ng-repeat="chapter in chapterList"> 
     <a ui-sref="books({chap: chapter.chapter})">{{chapter.chapter}}</a> 
    </li> 
</ul> 

你已經包括$ stateParams在您的控制器已經所以你只需要從中攫取參數,像這樣

angular 
.module('BookLibrary') 
.controller("ChapterController", ["$scope","$stateParams", 
"ChapterControllerService", function($scope, $stateParams, 
ChapterControllerService){ 

    $scope.currentChapter = $stateParams.chap; 

    $scope.chapterList = ChapterControllerService.chapters; 
    $scope.getArticle = chapterList[0].chapter; 

}]); 
相關問題