2013-10-16 120 views
0

所以這是我的工廠代碼:運行代碼後先

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

這是我的範圍內的代碼:

$scope.search = function() { 

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

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

}; 

我的問題是$scope.booleanValue = ($scope.arrayValue.length <= 0)$scope.arrayValue已從$simpleFactory.getArray($scope.searchWord)獲得其價值之前執行。
所以我的問題是我怎麼能等到功能的getArray完成火我的代碼:

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

回答

1

首先從工廠方法getArray返回promise

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

    factory.getArray = function (srchWord) { 

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

    return factory; 
}); 

其次等待承諾解決使用然後。

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

閱讀有關什麼promise是,如何$http使用它們。

+0

謝謝,我讀到的承諾,並設法解決這個問題:d – Erex

1

您可以將布爾值設置爲getArray函數的回調,也可以在arrayValue上設置監視並根據該值更新booleanValue。

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

}; 
+0

我想第二個選項,但我總是得到一個空數組,即使arrayValue不是空的...任何想法? – Erex

+0

我的編輯應該可以工作。 – Sharondio

+0

它與oldValue協同工作,但隨後一直落後於後面一步:P 出於某種原因,newValue總是返回一個空數組:/ – Erex