2016-07-15 66 views
0

這可能很容易,不知道。但我只是通過節點/快遞後端完成此操作。 但不太完全如何做到這一點,只與前端和一個json文件,我的數據是。 現在它顯示了我所有帖子的列表,但是我想單擊一個按鈕時獲得唯一的帖子:id。從AngularJS的json文件中獲取單個帖子的編號

一個簡單的posts.json文件:

[{ 
    id: 1, 
    title: 'Simple title1', 
    content: 'Sample content...', 
    permalink: 'simple-title1', 
    author: 'Peter', 
    datePublished: '2012-04-04' 
}, { 
    id: 2, 
    title: 'Simple title2', 
    content: 'Sample content...', 
    permalink: 'simple-title2', 
    author: 'Peter', 
    datePublished: '2012-05-04' 
}, { 
    id: 3, 
    title: 'Simple title3', 
    content: 'Sample content...', 
    permalink: 'simple-title3', 
     author: 'Thomas', 
    datePublished: '2012-06-04' 
}] 

這裏是我的app.js文件:

var routerApp = angular.module('routerApp', ['ui.router']); 

routerApp.config(function($stateProvider, $urlRouterProvider) { 

$urlRouterProvider.otherwise('/home'); 

$stateProvider 




.state('home', { 
    url: '/posts', 
    templateUrl: 'partial-home.html', 
    controller: function($scope, $http){ 
    $http.get('posts.json') 
    .success(function(data){ 
    $scope.posts = data; 
    }); 
    } 
}) 

      .state('viewdetails',{ 
    url:'/posts/:id/:permalink', 
    templateUrl: 'view_details.html', 
    controller: function($scope, $http){ 
    $http.get('source.json') 
    //get a single post here??? 
    } } 

有的在我的部分,home.html的代碼

<div class="row" style="margin-left:50px"> 
    <!--row left--> 
    <div class="col-xs-8 col-sm-4 col-md-3 col-lg-5 box-background" ng-repeat="post in posts"> 
    <!--column 1 left--> 
    <div class="col-md-4 img-space"> 
     <img class="img-circle" alt="Bootstrap Image Preview" src="{{prov.picture}}" /></div> 
    <div class="col-md-4"> 
     <h4>{{post.author}}</h4> 
     <p class="text-grey"> 
     {{post.content}} 
     </p> 
    </div> 
    <a ui-sref="posts/:id" class="btn btn-primary btn-color" style="width:100%">View details</a> 
    </div> 
    <!--end column 1 left--> 
</div> 
<!--end row left--> 

我知道這不是一個mvc模式,但只是想做到這一點很簡單。 以前只有用貓鼬,節點後端做過這個。所以希望有一些想法幫助。 謝謝。

回答

0

您將使用$ routeParams從您的路線獲取id,然後將其用作$ http請求url中的變量。 時,取相同sourse.json文件,你可以使用該ID來唯一正確的職位分配給您的視圖變量

https://docs.angularjs.org/api/ngRoute/service/ $ routeParams