数据库插入后AngularJS ng-repeat不更新

时间:2014-07-25 09:43:50

标签: angularjs angularjs-scope angularjs-ng-repeat

我是AngularJS的新手。我整夜都被困在这里。我有一个表单,我希望表单点击提交后添加新行。表单工作正常,并将文档添加到mongodb但我无法看到表上的更新与绑定,直到我刷新页面。

我错过了什么?我看到有关使用PUSH的示例,但这似乎只适用于一维数组。

ANGULARJS

app.factory('SiteFactory', function($resource) {
  return $resource('/api/sites/:id',{ id:'@_id' });
});

app.controller('SiteListController', function($scope, $location, SiteFactory) {

  // GET LIST OF SITES
  var sites = SiteFactory.query();
  $scope.sites = sites;

  $scope.createSite = function () {

    // validate data passed
    var domain = $scope.domain.trim();
    if (!domain.length) {
        return;
    }
    // POST to API
    var newSite = new SiteFactory();
    newSite.domain         = domain;
    newSite.created        = new Date();
    newSite.$save();

    console.log($scope.sites);
    $scope.sites = SiteFactory.query();
    console.log($scope.sites);
  };

HTML

<form ng-controller="SiteListController">
<input type="text" ng-model="domain">
<button type="button" ng-click="createSite()">SUBMIT</button>
</form>
...
<tbody>
<tr ng-repeat="site in sites | orderBy:'domain'">
<td>{{site.domain}}</td>
<td>{{site.created}}</td>
</tr>
</tbody>
...

CONSOLE.LOG

之前:

[f, f, $promise: Object, $resolved: true]
0: f
1: f
$promise: Object
$resolved: true
length: 2
__proto__: Array[0]

EXAMPLE:
    0: f 
    _id: "53d21d42f9406200001eddc6" 
    created: "2014-07-25T09:02:58.215Z" 
    domain: "originaldata1"
    1: f 
    _id: "53d21d42f9406200001eddc7" 
    created: "2014-07-25T09:02:58.215Z" 
    domain: "originaldata2"

AFTER:

[$promise: Object, $resolved: false]
0: f
1: f
2: f
$promise: Object
$resolved: true
length: 3
__proto__: Array[0]

EXAMPLE:
    0: f 
    _id: "53d21d42f9406200001eddc6" 
    created: "2014-07-25T09:02:58.215Z" 
    domain: "originaldata1"
    1: f 
    _id: "53d21d42f9406200001eddc7" 
    created: "2014-07-25T09:02:58.215Z" 
    domain: "originaldata2"
    2: f 
    _id: "53d21d42f9406200001eddc8" 
    created: "2014-07-25T09:12:58.215Z" 
    domain: "newdata2"

1 个答案:

答案 0 :(得分:2)

     $scope.createSite = function () {

        // validate data passed
        var domain = $scope.domain.trim();
        if (!domain.length) {
            return;
        }
        // POST to API
        var newSite = new SiteFactory();
        newSite.domain         = domain;
        newSite.created        = new Date();
        newSite.$save();
//please add new site to arrays of sites
        $scope.sites.push(newSite);

      };