VBAHole
VBAHole

Reputation: 1518

angularjs defer then only being called once

I am using the window object and a defer in order to inject some content into my controller that is not available at the time i create it. This is working fine the first time i call it - the .then method is being executed just fine. But when i call it subsequent times the .then method is not firing. What could cause this?

app.factory('fromoutside', function ($window, $q, $rootScope) {
    var deferred = $q.defer();

    $window.injectIntoAngularWorld = function (obj) {
        deferred.resolve(obj);
        $rootScope.$apply();
    };

    return deferred.promise;
});

This is a fiddle that sort of simulates what i'm doing but not exactly. It throws errors about apply already in progress, but then again, i get those alot and ignore them quite often fiddle

Upvotes: 2

Views: 1351

Answers (2)

Fredylg
Fredylg

Reputation: 11

I had the same issue and I fixed it by definin de deferred each time , i guess for you would be something like this :

$window.injectIntoAngularWorld = function (obj) {
    var deferred = $q.defer();
    deferred.resolve(obj);
    $rootScope.$apply();
};

Upvotes: 0

Ben Lesh
Ben Lesh

Reputation: 108501

You're probably going to be better off using an event for this sort of thing.

Promises are made to be resolved and then they're done. So that means they're kind of a one shot deal.

Here's what I'm proposing:

//set it up in your run block.
app.run(function($rootScope, $window) {
   $window.foo = function (data) {
        $rootScope.$broadcast('fooCalled', data);
   };
});


//use $on in your controller.
app.controller('MyCtrl', function($scope){ 
   $scope.$on('fooCalled', function(event, data) {
      $scope.fooData = data;
   });
});

This is just one way to do it, but it should work, and it's fairly clean. If you wanted to create a service to listen to the event and set it up, you could.

Upvotes: 4

Related Questions