Ray Za
Ray Za

Reputation: 13

How to make a promise's then function work when the promised is resolved in a watch function?

I'm trying to fire some code after and when a user has made a selection from select menus. Therefor I was trying to use promises and the $scope.$watch function. I'm resolving the promise in that watch function but the then function of the promise doesn't get fired. $scope.$apply() doesn't seem to work in this context. How can I get this then function to fire?

Here's the code:

var nameSpace = angular.module("test", []);
nameSpace.controller("DataRetriever", ['$scope','$http', '$q', function($scope, $http, $q)
{
    $scope.options = ["1","2","3"];
  $scope.displayText = false;
    console.log("options set");
    var deferred = $q.defer();
    $scope.selectedOption = "";
    $scope.$watch("selectedOption", function (newValue, oldValue) {
        if (newValue != "") {
            deferred.resolve(newValue);
            console.log("Resolve called! New value: ", newValue);
        } else {
            deferred.reject("Invalid option!");
        }
    });
    deferred.promise.then(function(data){
        $scope.displayText = true;
        console.log("Then success callback function executed!");
    });
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="DataRetriever as dr">
<select ng-model="selectedOption"><option ng-repeat="option in options">{{option}}</option>
</select>
  <div ng-show="displayText">Then success callback function executed!</div>
</div>

Upvotes: 0

Views: 463

Answers (2)

Chandermani
Chandermani

Reputation: 42669

Why you code is not working is because the first resolution is a reject, you can verify by adding console.log in the else condition. Once rejected the promise cannot be changed, and hence the behaviour.

@PSL is right use standard ng-change

Upvotes: 0

dbarnes
dbarnes

Reputation: 1833

Promises will only be resolved once so the first time will succeed and do what you want but anytime after that it won't resolve it again. [Ref] so what you are trying to accomplish is not possible with promises.

Upvotes: 1

Related Questions