Question

So this is my factory code:

app.factory('simpleFactory', function ($http) {
   var factory = {}; 

     factory.getArray = function (srchWord) {

         **Here i have a code that uses $http to fill a array called result with values.

           return result;
      };

    return factory;
});

And this is the code inside my scope:

 $scope.search = function() {

        $scope.arrayValue = simpleFactory.getArray($scope.searchWord);

        $scope.booleanValue = ($scope.arrayValue.length <= 0); // <-- PROBLEM! This gets executed before getArray() is finished.

 };

My problem is that $scope.booleanValue = ($scope.arrayValue.length <= 0) is executed before $scope.arrayValue has gotten its value form $simpleFactory.getArray($scope.searchWord).
So my question is how I can wait until the getArray function is finished to fire my code:

$scope.arrayValue = simpleFactory.getArray($scope.searchWord);
Was it helpful?

Solution

Firstly return a promise from the factory method getArray.

app.factory('simpleFactory', function ($http) {
   var factory = {}; 

     factory.getArray = function (srchWord) {

         return $http.query(....);  // this returns promise;
      };

    return factory;
});

Secondly wait for the promise to resolve using then.

scope.arrayValue = simpleFactory.getArray($scope.searchWord).then(function(data) {
   $scope.arrayValue=data;
   $scope.booleanValue = ($scope.arrayValue.length <= 0);
});

Read about the what promise is, how $http uses them.

OTHER TIPS

You can either set the boolean value as a callback of the getArray function, or you can set a watch on the arrayValue and update the booleanValue based on that.

$scope.search = function() {

    simpleFactory.getArray($scope.searchWord, function(result) {
        $scope.arrayValue = result;
        $scope.booleanValue = ($scope.arrayValue.length <= 0);
    });

    // or

    // initialize the value
    $scope.arrayValue = [];

    // *then* set the value, so it triggers the change on the $watch below    
    $scope.arrayValue = simpleFactory.getArray($scope.searchWord);

    $scope.$watch('arrayValue', function(newValue,oldValue) {
        $scope.booleanValue = (newValue.length <= 0);
    });

 };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top