db-update更新后ng-repeat不更新

时间:2016-05-27 15:44:25

标签: javascript html angularjs mongodb

我在Mongo数据库中创建新项目后尝试让我的ng-repeat更新。根据我的研究,这应该是自动发生的。我知道,对于每个视图,为该视图创建一个新的$ scope,并在所有$ scope之间共享数据,你将使用一个服务,我相信我正在做的...但也许不是。

感谢任何帮助,这是我的代码:

newblog.html

<div class="newblog">
<a ui-sref="blogs"><i class="fa fa-close fa-2x exit"></i></a>
<div class="form">
      <form>
            <i class="fa fa-pencil-square-o fa-5x"></i><br>

            <input class="blogtitle" type="text" ng-model="formData.title" placeholder="Blog Title" required /><br>

            <textarea ng-model="formData.body" rows="15" placeholder="Write the body of your blog here." required></textarea><br>

            <label for="">by:</label><br>
            <input class="blogauthor" type="text" ng-model="formData.author" placeholder="Author Name" required /><br><br>

            <button type="submit" ng-click="addPost()">Submit</button>  
      </form>
</div>

以下是用户创建的新博客的表单。

main.html中

<div class="wrapper"> 
    <div class="blog-container" ng-repeat="data in blog | orderBy: '-pubdate'" ng-click="readPost(data._id)" ui-sref=".readblog">  
        <p><i class="fa fa-sticky-note"></i>&nbsp;<b>{{ data.title }}</b></p>
        <p>by {{ data.author }}</p> 
        <p>{{ data.pubdate | date }}</p>
        <br>
        <div>
            <p>{{ data.body }}</p>
        </div>
        <br><br>
    <div class="button-box">
        <div id="deletePost" ng-click="deletePost(data._id)"><i class="fa fa-trash-o fa-2x"></i></div>
    </div>
</div>

以下是ng-repeat的视图。

以下是我的控制器和服务。

mainCtrl.js

var app = angular.module("blog-app");

app.controller('MainController', ['mainService', '$scope', '$http', '$location', '$stateParams', '$state', function(mainService, $scope, $http, $location, $stateParams, $state) { 

$scope.formData = {};

$scope.blog = mainService.blog;

function getBlogs() {
  mainService.getPosts().then(function(data) {
    $scope.blog = data;
    console.log(data, "The blogs.");
  });
}

getBlogs();

$scope.addPost = function(data) {
      mainService.addPost($scope.formData).then(function(data) {
        $scope.formData = {};
        $location.path('blogs');
        $scope.blog.push(data);
        console.log(data, 'Blog created.');     
      }); 
        getBlogs();
  };

}]); //End Controller.

mainService.js

var app = angular.module("blog-app");

app.service('mainService', function($http, $q) {

    var blog = [];
    var readblog = {};
    var formData = {};

    this.getPosts = function() {
        return $http.get('/api/blogs').then(function(response){
            blog = response.data;
            return blog;
        });
    }

    this.readPost = function(id) {
        return $http.get('/api/blogs/' + id).then(function(response) {
            readblog = response.data;
            return readblog;
      });
    };

    this.addPost = function(formData) {
        return $http.post('/api/blogs', formData).then(function(response) {
            blog = response.data;
        })
    };

});

我的 server.js ...

    //Dependencies.
var express = require('express');
var router = express.Router();
// var sendgrid  = require('sendgrid')(process.env.U, process.env.PASSWORD)
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoose = require('mongoose');
var mongojs = require('mongojs');
var http = require('http');
var path = require('path');
var fs = require('fs');
var dotenv = require('dotenv');

var port = 9001;
var mongoUri = 'mongodb://localhost:27017/blog-app';

var app = express();

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

//Blog Data & Data Storage.
//_________________________________________________________________________________________________________________________


var Schema = mongoose.Schema;

var blogSchema = new Schema({
    title : {type: String, min: 8, max: 50, required: true},
    body : {type: String, required: true},
    author : {type: String, min: 3, max: 40, required: true},
    pubdate : {type: Date, default: Date.now}
});

var Blog = mongoose.model('Blog', blogSchema);

//Routes.
//_________________________________________________________________________________________________________________________

// GET BLOGS!
app.get('/api/blogs', function(req, res) {
    Blog.find(function (err, blogs) {
        if (err)
            res.send(err);
        res.json(blogs);
    });
});

app.post('/api/blogs', function(req, res) {
    Blog.create({
        title: req.body.title,
        body: req.body.body,
        author: req.body.author,
        date: req.body.date
    }, function(err, blog) {
        if (err)
            res.send(err);
        Blog.find(function(err, blogs) {
            if (err)
                res.send(err);
            res.json(blogs);
        });
    });
});

mongoose.connect(mongoUri);
mongoose.connection.once('open', function() {
  console.log("Hey there! We are now connected to MongoDB at: ", mongoUri);
});

app.listen(port, function() {
  console.log('Magic! Listening on port: ', port);
});

我已经在两天内完成了这项工作,非常感谢任何帮助!

3 个答案:

答案 0 :(得分:1)

一个问题可能是您在检索博客之前没有等待发布新帖子。

尝试在getBlogs()来电的回调中移动addPost来电:

$scope.addPost = function(data) {
  mainService.addPost($scope.formData).then(function(data) {
    $scope.formData = {};
    $location.path('blogs');
    $scope.blog.push(data);
    console.log(data, 'Blog created.');

    getBlogs();   
  }); 
};

答案 1 :(得分:0)

在你的addPost()处理程序中,你可以通过push()将新帖子添加到博客数组中,或者通过调用getBlogs()重新加载博客,这些调用应该在promise完成之后。

第一种方法:使用formData

  $scope.addPost = function(data) {
      mainService.addPost($scope.formData).then(function(data) {

        var newItem = jQuery.extend({}, $scope.formData); // copy the new inserted item from formData
        // newItem._id = data; // uncomment this to set the id
        $scope.blog.push(newItem); // this should be enough to update the repeater
        $scope.formData = {}; // clear formData
      }); 

  };

第二种方法:重新加载所有帖子

  $scope.addPost = function(data) {
      mainService.addPost($scope.formData).then(function(data) {
        getBlogs();
        $scope.formData = {};
      }); 

  };

答案 2 :(得分:0)

所以,这可能是一种hacky方式,但它完全符合我的要求。在我的控制器中,在addPost函数中,我添加了

$state.go('blogs).then(function() {
  $state.reload('blogs');
});

......所以它看起来像这样......

$scope.addPost = function(newBlog) {
  mainService.addPost(newBlog).then(function(data) {
    $scope.blog = data;
    console.log(data, 'Blog created.');
    $state.go('blogs').then(function() {
      $state.reload('blogs');
    })
  }); 
};

我基本上只是回到ng-repeat所在的范围,然后重新加载它。它很棒。但是,如果还有其他任何替代方案,我确信有这些方案,如果有人愿意与他们分享,我会非常感激和欣赏它。

如果有人能够启发我可能会产生的错误或未来的错误,也会感激不尽。到目前为止,我还没有看到任何内容,但我对AngularJS还是比较绿色,所以欢迎任何想法/评论。