如何使保存的对象立即出现在ng-repeat中?

时间:2016-01-11 04:14:39

标签: javascript angularjs

JS:

  $scope.addPano = function () {
      var Pano = AV.Object.extend("Panorama"),
      pano = new Pano()

      var json = {
        'name': 'test3',
        'index': 0,
        'Type': 'real',
        'version': 0,
        'buildingCode': $scope.buildingId
      }

      pano.save(json, {
    success: function(object) {
      console.log('PANO: ', object)
      $scope.building.pano.push(json)
      $scope.$digest()
    },
    error: function(object, error) {
      console.log('Failed to create new object, with error message: ' + error.message);
    }
      })
    }

HTML:

<div ng-repeat="pano in building.pano">
  <p><strong>{{pano.name}}</strong></p>
  <div ng-repeat="panodata in pano.panoData">
    <p>{{panodata.name}}</p>
  </div> <a class="btn btn-default" href="javascript:;" ng-click="addPanodata(pano.objectId)">Add panodata</a> </div> <a class="btn btn-default btn-lg" href="javascript:;" ng-click="addPano()">Add pano</a>
</div>

现在唯一能让它出现的方法是:

      $scope.building.pano.push(json)
      $scope.$digest()

我认为Angular会自动执行此操作吗?

2 个答案:

答案 0 :(得分:1)

我认为您可以尝试这种类型但是在您的代码中,您在保存方法调用成功后重新加载数据,然后您可以轻松地轻松显示...

function myctrl($scope){
  $scope.data =[{name:'abc'}];
  
  $scope.pushdata = function(name){
    $scope.data.push({name});
    $scope.name ='';
    
  }
}
<html ng-app=''>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    </head>
  <body ng-controller='myctrl'>
      <input type='text' name='name' ng-model='name'/>
    <button name='clickme' type=submit ng-click='pushdata(name)'>save</button>
    <div ng-repeat='obj in data'>
      {{obj.name}}
    </div>
  </body>
  </html>

答案 1 :(得分:1)

执行此操作的官方方法是编写pano服务以支持角度。那么你在服务中调用成功回调的地方:

.factory('pano', function() {
  return {
    save: function(x, options) {
      setTimeout(function() {
        options.success(123);
      }, 1000);
    }
  };
});

你应该把它包装在$ scope中。$ apply这样angular就有机会运行脏检查:

.factory('pano', function($rootScope) {
  return {
    save: function(x, options) {
      setTimeout(function() {
        $rootScope.$apply(function() {
          options.success(123);
        });
      }, 1000);
    }
  };
});

同样适用于错误处理回调。

注意:内置角度服务,例如$http$q$timeout会自动执行此操作。