Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm learning AngularJs and I'm facing a problem.

I want to show an array of items in a view. First in the controller I define the array using $scope.arrName = [], then I receive data from a third party service and add it to the array with $scope.arrName.push(data[i]). I figured it out that in order to my view render the changes I have to insert $scope.$apply after pushing data to the array.

Is there a way to modify the array and render the changes without $scope.$apply? Why code breaks if I change $scope.arraName with this.arrName? (it throws Uncaught TypeError: Cannot read property 'push' of undefined)

Reference code

Controller

angular.module('testApp')
  .controller('testCtrl', function($scope) {

    $scope.objects = [];

    var service = new thirdPartyService();

    service.getData(function(err, data) {
      if (err) {
        console.log('Error');
      } else {
        for (var i = 0; i < data.Contents.length; i++) {
          $scope.objects.push(data.Contents[i].Key);
          $scope.$apply();
        }
      }
    });
  });

View

Just an ng-repeat to show the data

share|improve this question

2 Answers 2

  • this.arrName does not exist because you didn't create a local var arrName, you appended a arrName field to the $scope, which is a distinct entity from your controller.
  • As for your rendering, have you simply tried without the $apply ? Your ng-repeat should detect any changes in the backing array and update accordingly.
share|improve this answer
    
Is the same. If I write var arrName = [] before setting it to this.arrName, nothing changes. And I don't know why the model don't keep track of arrName, I have to manually $scope.$apply to push changes to the view. –  wOvalle Oct 5 at 4:19

I typically pass a callback to $apply...

$scope.$apply(function(){
   $scope.objects.push(data.Contents[i].Key);
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.