0

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);

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, i read about promises, and managed to fix the problem :D
1

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);
    });

 };

2 Comments

i tried the second option, but i always get a empty array, even though arrayValue is not empty... Any ideas?
it works with oldValue, but then its obiously one step behind all the time :P For some reason newValue always return an empty array :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.