0

In my main app controller, I'm calling this async method which is broadcasting an event when done (loadData). In the event handler i'm loading some data to my $scope.layers array. But nothing is shown in my view.

The event is being fired and data is populated into the layers array.

This is the view:

<div ng-repeat="layer in layers track by $index">
     <span>{{layer.name}}</span>
</div>

This is my controller

app.controller('MainPanelCtrl',['$scope', 'myService', function($scope, myService){
'use strict';

myService.loadData();

$scope.$on('loadDoneEvent', function () {
    $scope.layers = myService.getLayers();
    //$scope.$apply() // why when adding this its working?
});}]);

This is the service:

app.factory('myService', ['$rootScope', '$http', function ($rootScope, $http) {
    'use strict';
     var data;

    var loadData = function (compId) {
        $http.get("someUrl").then(function (response) {
            data = response.data;
            $rootScope.$broadcast('loadDoneEvent');
        });
    };
  return {
           loadData : loadData 
        };
    }]);

I just can't get what i'm missing here...

I know I can use promises and it will work. But I want to be able to call this loadData function more than once and that my different UI components to response. Not sure if I can get this with promises.

I found this link and it's working for him so I just can't understand why it's not working for me...

Tamar Cohen
  • 1,182
  • 2
  • 14
  • 28
  • why are you broadcasting data from service? It would be better to return a promise and then in the callback update your array – Gonzalo.- Mar 07 '17 at 19:36
  • Also, you might want to check this http://stackoverflow.com/questions/35951408/ng-repeat-is-not-updating-when-array-is-changed and this http://stackoverflow.com/questions/29849293/ng-repeat-not-updating-on-update-of-array – Gonzalo.- Mar 07 '17 at 19:43
  • 1
    Could you show us how` myService.loadData()` works? As it stands this code would never work because you aren't actually using `$scope.$broadcast` or `$scope.$emit` in what you have shown. – Jon Black Mar 07 '17 at 21:08
  • I think he's injecting $rootScope on the service and using $broadcast - something that I don't recommend – Gonzalo.- Mar 07 '17 at 21:52
  • See [How to Pass data from Third-Party Library Callback to View in AngularJS](http://stackoverflow.com/questions/42508380/how-to-pass-data-from-third-party-library-callback-firebase-to-view-in-angular/) – georgeawg Mar 07 '17 at 21:56

0 Answers0