AngularJS:如何在视图中的$ scope变量中呈现HTML?

时间:2017-12-05 10:24:03

标签: javascript angularjs node.js html5 mean-stack

我一直在尝试使用MEAN堆栈创建博客应用。我有问题将帖子呈现为HTML。在浏览器上,它只显示{{posts}}

HTML code:

<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
    <head>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script src="app.js"></script>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <div class="container" ng-controller="BlogController">
            <h1>Blog</h1>
            <input ng-model="post.title" class="form-control" placeholder="title"/>
            <textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
            <button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>

            {{posts}}

        </div>
    </body>
</html>

角度代码:

(function() {
    angular.module("BlogApp", []).controller("BlogController", BlogController);
    function BlogController($scope, $http) {
        $scope.createPost=createPost;

        function init() {
            getAllPosts();
        }

        init();

        function getAllPosts() {
            $http.get("/api/blogpost").success(function(posts) {
                $scope.posts=posts;
            });
        }

        function createPost(post) {
            console.log(post);
            $http.post("/api/blogpost", post);
        }
    }
})();

2 个答案:

答案 0 :(得分:0)

由于您使用的是角度1.6.x,因此必须使用.then.catch而不是.success.error,因为后者在较新版本中已弃用。< / p>

  (function() {
        angular.module("BlogApp", []).controller("BlogController", BlogController);
        function BlogController($scope, $http) {
            $scope.createPost=createPost;

            getAllPosts();

        function getAllPosts() {
                $http.get("/api/blogpost").then(function(response) {
                    $scope.posts=response.data; //check if this is what you are looking for
                });
            }

            function createPost(post) {
                console.log(post);
                $http.post("/api/blogpost", post);
            }
        }
    })();

答案 1 :(得分:0)

您的getAllPosts函数应使用 .then 而不是 .success ,因为.success不推荐使用1.3以上的角度版本

  function getAllPosts() {
     $http.get("/api/blogpost").then(function(response) {
         $scope.posts=response.data; 
      });
   }