Thomas Thomas - 5 months ago 19
AngularJS Question

Update ng-repeat after function

I have build a piece of angular code but the ng-repeat should show after i called the function. I checked if the http.get function actually returns data and that is true it returns a list formatted like this:

[{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
}
}]);


})();

Answer

You don't need the transformResponse function, just remove it entirely.

Also, I believe when using the syntax controller as somevariable, you should assign things to the scope using this instead of $scope.

So in your case, change $scope.documents = driveLoad.files; to this.documents = driveLoad.files;

Other than that, your code is correct as far as I can see.

Correct code:

(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
    }
  }]);


})();