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)之前执行。 所以我的问题是我如何才能等到 getArray 函数完成来触发我的代码:$scope.arrayValue$simpleFactory.getArray($scope.searchWord)

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

2 回答 2

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

 };
于 2013-10-16T13:51:29.967 回答
1

首先promise从工厂方法返回一个getArray

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

     factory.getArray = function (srchWord) {

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

    return factory;
});

其次,使用 then 等待 promise 解决。

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

阅读它们是什么promise,如何$http使用它们。

于 2013-10-16T13:48:36.263 回答