2016-03-25 54 views
0

我有一個tableofcontent.html文件中的文章列表,它們都是可點擊的鏈接。此頁面正常工作,並顯示所有標題的列表。當我點擊鏈接時,它會轉到正確的模板文件,但沒有任何正確的數據填充在article.html文件中。如何讓每個鏈接的數據在articles.html頁面中正確顯示?爲ng-repeat創建動態鏈接

tableofcontent.html

<div class="row" ng-controller="TableofContentController"> 
    // non relevant code removed 
    <ul> 
     <li ng-repeat="article in data"> 
      <a ui-sref="article">{{article.title}}</a> 
     </li> 
    </ul> 

article.html

<div class="row" ng-controller="ArticlesController"> 
    // non relevant code removed 
    <h3>{{article.title}}</h3> 
    <h6>Author: {{article.author}} on {{article.date}}</h6> 
    <p>{{article.body}}</p> 
    //etc 

app.js

// service to retrieve and share data 

articleApp.factory('Data', function ($timeout, $http) { 
    var articles = { 
     fetch: function() { 
      return $timeout(function() { 
       return $http.get('articles.json') 
       .then(function(response) { 
        return response.data; 
       }); 
      }, 30); 
     } 
    } 
    return articles; 
}); 


articleApp.controller('TableofContentController', function ($scope, Data) { 
    Data.fetch().then(function(data) { 
     $scope.data = data; 
    }); 
}); 

articleApp.controller('ArticlesController', function ($scope, Data) { 
    Data.fetch().then(function(data) { 
     $scope.data = data; 
    }); 
}); 

也app.js

// table of content state 
.state('tableofcontent', { 
    url: '/index', 
    templateUrl: 'templates/tableofcontent.html' 
}) 
// main articles page state 
.state('article', { 
    url: '/{{article.title}}', 
    templateUrl: 'templates/articles.html', 
    controller: 'ArticlesController', 
    controllerAs: 'articles', 
}) 

回答

0

實際上有一堆的問題在這裏,你想要做的是,當有人點擊,而不是做

<a ui-sref="article">{{article.title}}</a> 

你可能想要做

<a ui-sref="article({id : article.id})">{{article.title}}</a> 

這些鏈接的名單上,現在您傳遞了文章的ID,需要修改模塊狀態定義以接受此文章ID,如下所示。

.state('article', { 
    url: 'article/:id', 
    templateUrl: 'templates/articles.html', 
    controller: 'ArticlesController', 
    controllerAs: 'articles', 
}) 

當你點擊文章那麼現在,你應該看到一個網絡請求,看起來像這樣:article/1234其中1234是所選文章的ID。

在這個例子中,您似乎總是加載相同的article.json數據,但是當與服務器交互時,您可以通過使用$stateParams服務訪問選定的文章ID,您可以將其注入控制器。

+0

嗨,我很欣賞這個建議。我不確定它是否可以工作,我已經嘗試過了,現在我的網站不會路由到文章狀態。所以現在我還有其他東西需要修復! – Seattlite