Chris
Chris

Reputation: 25

AngularJS Waiting for $resource Promise in the Scope of a User Click

I'm pretty new to front end / AngularJS development and have read (but don't completely understand) a lot of stack overflow questions and other documentation about ng-resource / $resource and promises. I have kind of a weird situation.

I have this code in a submit function for when the user clicks a button to submit a form.

        var Resource = $resource("/urlHere",{},{save: {method:'POST', isArray:true}});
        Resource.save(JSON.stringify($scope.validQuery)).$promise.then(function(data) {

        $scope.initialResults=data;

        if($scope.initialResults.length === 0){
           alert("No Results Found!");

        }else if($scope.initialResults.length === 1){
            window.data = $scope.initialResults;
            window.open('/detailedResults');

       }else if($scope.initialResults.length > 1){
            window.data = $scope.initialResults;
            var popupWindowResults = window.open('/resultsGrid');
        }
      });

I need to open a certain tab depending on how many results I get. (Basically show a grid with multiple results to choose from or just show the single result if only 1 is returned) Using window.open works fine when it's not contained within the $promise.then. Within the $promise.then, the browsers are treating it as a pop-up and not a new tab as the result of the user clicking something.

Is there a way to just halt execution until the results are returned so that I can open a tab outside of the $promise.then and in the submit function? Any solution would be extremely helpful.

Upvotes: 1

Views: 876

Answers (1)

Clint Powell
Clint Powell

Reputation: 2398

http://jsfiddle.net/az066xcs/2/

$scope.getResults = function() {
    var win = window.open();

    // this is a placeholder for the async call that gets results
    setTimeout(function() {
        win.document.write('<h1>Results Loaded!</h1>');
    }, 1000);
};

You can open the window on click, then load results async and insert them into the new window. Obviously, a better solution than a blank window with document.write would be to have another angular app in the new window, or at least a simple javascript application.

Upvotes: 1

Related Questions