2

I am having trouble with angularjs when after retrieving data from a rest service.

I am currently using the code from this SO question enter link description here to display my data.

myApp.directive('myTable', function () {
return {
    restrict: 'E',
    link: function (scope, element, attrs) {
        var html = '<table>';
        angular.forEach(scope[attrs.rows], function (row, index) {
            html += '<tr><td>' + row.name + '</td></tr>';
            if ('subrows' in row) {
                angular.forEach(row.subrows, function (subrow, index) {
                    html += '<tr><td>' + subrow.name + '</td></tr>';
                });
            }
        });
        html += '</table>';
        element.replaceWith(html)
    }
}
});

To get data from my rest service, I use this code:

app.factory("Entry", function($resource) {
        return $resource("/path/to/api:id");
    }); 

    app.controller("PostIndexCtrl", ['$scope', 'Entry', function($scope, Entry) {
        $scope.entries =[];
        Entry.query(function(data) {
    $scope.entries = data;
        });
    }]); 

I can retrieve the code data but for some reason, the in my html is not being updated after the data is received. It's as if the two way data binding is broken.

By the way, if I use ng-repeat on a list, it works.

This is what's on my html:

<my-table rows='entries'></my-table>
Community
  • 1
  • 1
Francis Zabala
  • 1,037
  • 2
  • 11
  • 30

1 Answers1

2

There are a couple of issues with your code. The first is the way you declared the rows attribute in the directive. Currently it is just a string value. Here's how to fix your code:

<my-table ng-if="entries.length>0" rows="entries"></my-table>

Here we are deferring the execution of the directive until our AJAX call has finished using ng-if. Next the directive declaration:

app.directive('myTable', function () {
    return {
        restrict: 'E',
        scope: { rows: '=' },
        link: function (scope, element, attrs) {
            // At this stage you can use the scope.rows value
            // which will contain the result from your AJAX call
        }
    };
});

Notice the scope: { rows: '=' } which allows for passing complex parameters from the parent scope to the directive and not just string values as in your example.

Once the link function is executed you can use scope.rows variable which will contain the actual data retrieved from your $resource.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928