Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger ng-repeat

Tags:

angularjs

I've just retrieved JSON data back from my database, in my success callback I update a $scope.requests array which should update my DOM. However, nothing happens even though the array's value has changed.

I'm pretty new to Angular so I am probably missing something fairly straight forward:

Callback code: (part of FetchUserCtrl)

// Success callback from server - returns the data from PHP file
callback.success(function(data) {

        // Build the request array to update DOM
        for (var i = 0; i < data.length; i++) {
            $scope.requests.push( { name: data[i].name, dob: data[i].dob } );
        }

        $scope.apply(); <-- I read that this should apply changes.
});

HTML

<aside id="previousFeed" ng-controller="FetchUserCtrl">
    <div class="priorResult" ng-repeat="request in requests">
        <p>{{ "hi" }}</p>
    </div>
</aside>

What I want to happen, is when the $scope.requests array is changed in my success callback, a div should be drawn for each object in the $scope.requests array.

What have I done wrong here?

like image 303
Halfpint Avatar asked Feb 23 '26 13:02

Halfpint


1 Answers

I think you should do like this.

$scope.$apply(function() {
   for (var i = 0; i < data.length; i++) {
     $scope.requests.push( { name: data[i].name, dob: data[i].dob });
   }
});

or something like this

$scope.$apply(function() {
   var request = [];
   for (var i = 0; i < data.length; i++) {
     requests.push( { name: data[i].name, dob: data[i].dob });
   }

   $scope.$apply(function() {
     $scope.requests = request;
   });
});
like image 121
Vicruz Avatar answered Feb 25 '26 03:02

Vicruz