功能后更新ng-repeat

时间:2014-08-15 08:28:10

标签: angularjs

我已经构建了一段角度代码但是ng-repeat应该在我调用函数后显示。我检查了http.get函数是否实际返回数据,这是真的,它返回一个格式如下的列表:

[{id:"183m-WQHGaNHP-uVhuvJONyVKLAG", title:"a title"},{id:"183m-WQHGaNHP-uVhuvJONyVKLAG", title:"a title"}]

HTML:

<body ng-controller="driveController as drive">
<div ng-repeat="f in drive.documents">
  <pre>{{f | json}}
  </pre>
</div>
</body>

JS:

(function() {
  var app = angular.module('app', []);

  app.controller('driveController', ['$scope', 'driveLoad', function($scope, driveLoad) {

    $scope.documents = driveLoad.files;
    driveLoad.getFiles("root"); 

  }]);

  app.service('driveLoad', ['$http', function($http, id) {
    var files = [];
    var jsonTransform = function (data, headers) {
      return angular.fromJson(data);
    };
    return {
        getFiles: function (id) {
          $http.get('/svc', {
            transformResponse:jsonTransform,
            params:{'file_id':id}
          }).success(function(data, status, headers, config) {
            angular.copy(data, files);
          });
        },
        files: files
    }
  }]);


})();

1 个答案:

答案 0 :(得分:1)

您不需要transformResponse功能,只需将其完全删除即可。

此外,我相信在使用语法controller as somevariable时,您应该使用this而不是$scope将内容分配给范围。

因此,在您的情况下,请将$scope.documents = driveLoad.files;更改为this.documents = driveLoad.files;

除此之外,就我所见,你的代码是正确的。

正确的代码:

(function() {
  var app = angular.module('app', []);

  app.controller('driveController', ['$scope', 'driveLoad', function($scope, driveLoad) {

    this.documents = driveLoad.files;
    driveLoad.getFiles("root"); 

  }]);

  app.service('driveLoad', ['$http', function($http, id) {
    var files = [];
    return {
        getFiles: function (id) {
          $http.get('/svc', {
            params:{'file_id':id}
          }).success(function(data, status, headers, config) {
            angular.copy(data, files);
          });
        },
        files: files
    }
  }]);


})();