首页 > 解决方案 > AngularJS:为单个帖子制作页面

问题描述

我正在用 AngularJS 制作一个博客应用程序。我有一个主页,显示所有帖子,但我也希望能够单击帖子并转到其页面。数据存储在 MySQL 数据库中。

主页上显示的帖子:

<ul>
    <li ng-repeat="post in posts track by $index" id="content">
    <h1><a href="#!/post/{{post.id}}">{{ post.title }}</a></h1>
    </br>
    <h2>{{ post.content }}</h2>
    </li>
  </ul>

单个帖子的页面:

<h1>{{ post.title }}</h1>
</br>
<h2>{{ post.content }}</h2>

在 addremove.php 中通过 PHP 获取数据(由主页使用):

if($request_type == 1){
  $stmt = $con->prepare("SELECT * FROM posts");
  $stmt->execute();
  $result = $stmt->get_result();
  $data = array();
  if($result->num_rows > 0){
     while($row = $result->fetch_assoc()) {
            $data[] = array("id"=>$row['id'],"title"=>$row['title'],"content"=>$row['content']);
     }
  }

  $stmt->close();
  echo json_encode($data);
  exit;
}

通过主页控制器(HomeController)传递的数据:

$http({
  method: 'post',
  url: 'addremove.php',
  data: {request_type:1},

 }).then(function successCallback(response) {
  $scope.posts = response.data;
 });

我在使用单个帖子的控制器 (SinglePostController) 时遇到问题。我不知道如何通过它的 id 只显示一个帖子。我尝试了以下方法:

blogApp.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
    $http({
  method: 'post',
  url: 'getSinglePost.php',
  data: {
        request_type:1,
        id: $routeParams.postid
    },

 }).then(function successCallback(response) {
  $scope.posts = response.data;
 });
    }]);

我制作了一个 getSinglePost.php 文件,如下所示:

<?php
    include 'config.php';

     $post = json_decode(file_get_contents("php://input"));
     $id = $post->id;

     $request_type = $data->request_type;

     if($request_type == 1){
       $stmt = $con->prepare("SELECT * FROM posts");
       $stmt->execute();
       $result = $stmt->get_result();
       $data = array();
       if($result->num_rows > 0){
          while($row = $result->fetch_assoc()) {
                 $data[] = array("id"=>$row['id'],"title"=>$row['title'],"content"=>$row['content']);
          }
       }

       $stmt->close();
       echo json_encode($data);
       exit;
     }
?>

标签: phpmysqlangularjs

解决方案


主页

  • 帖子 1
  • 帖子 2

当我单击post 2时,它转到 /#/!/post/2

在单张贴状态配置中

$routeProvider.when('/post/:postid', {
 // this is how to set the variable for the post id
     controller: 'SinglePostController'
                    

在单个博客页面控制器中

blogApp.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
$http({
  method: 'post',
  url: 'getSinglePost.php',
  data: {
    request_type:1,
    id: $routeParams.postid
  },

 }).then(function successCallback(response) {
  $scope.post = response.data;
 });

然后在你的 PHP

 <? // getSinglePost.php
     $post = json_decode(file_get_contents("php://input"));
     $id = $post->id;

// get single blog info from database and echo it back with json_encode()

推荐阅读