1

I'm having trouble keeping 2 controllers in sync when using my factory/service.

I have (slightly minified)

angular.factory('API', ['$http', function($http){

    let self = this;

    self.scans = [];

    self.updateHistory = function (cb) {
        return $http.get('/scanner/history').then(function(scans){
            self.scans = scans.data;
            if (cb) {
                return cb(self.scans);
            } else {
                return self.scans;
            }
        }, function(err){
            console.error(err);
        });
    };

    return self;
 }]);

Then my controllers

angular.controller('NewCrawl', ['$scope', 'API', function ($scope, API) {

    $scope.scan = {
        url: null
    };

    $scope.startScan = function () {
        if ($scope.scan.url) {
            API.start($scope.scan.url)
            .then(function(){
                API.updateHistory();
            });
        }
    };
}])

and

angular.controller('ScanHistory', ['$scope', 'API', function($scope, API){
    $scope.scans = API.scans;
    API.updateHistory();
}])

I then have a ngRepeat within my ScanHistory controller like

<tbody>

    <tr ng-repeat="scan in scans | orderBy:'id':true">
        <td><% scan.id %></td>
        <td><% scan.url %></td>
        <td><% scan.started %></td>
        <td><% finishedText(scan) %></td>
        <td><% scan.errors.length %></td>
    </tr>

</tbody>

So thats basically the setup, the problem is - when I run API.updateHistory() it fires, and if i console.log(self.scans)' within the service i get the expected result.

However my ngRepeat does not update with the newly added item, even though the API.updateHistory method returned the correct results.

Why!?

owenmelbz
  • 6,180
  • 16
  • 63
  • 113

1 Answers1

0

well the API.updateHistory() will only fire in NewCrawl controller when you invoke the $scope.startScan function. It doesn't affect the other controller (ScanHistory) because they are not connected even you inject the API service there. If you want to sync the two controller, use $rootscope. I think you can get some idea in this post How to call a function from another controller in angularjs?

Community
  • 1
  • 1
pryxen
  • 381
  • 2
  • 22
  • I was under the impression as it was by reference it would be synced across :( – owenmelbz Feb 06 '17 at 11:17
  • I have a question sir. Is your `ng-repeat` working? – pryxen Feb 07 '17 at 01:30
  • I think it is working even you don't have a $rootscope. The problem is the way you call your data in your ng-repeat. Please check this http://plnkr.co/edit/DaLtcRREtkctpdf0FkfH?p=preview – pryxen Feb 07 '17 at 01:43