2013-10-16 5 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)을 얻기 전에 실행됩니다.

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

답변

1

우선 팩토리 메소드 getArray에서 promise을 반환 :
그래서 내 질문은의 getArray 기능이 내 코드를 해고 완료 될 때까지 기다릴 수있는 방법입니다.

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

    factory.getArray = function (srchWord) { 

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

    return factory; 
}); 

두 번째로 다음 약속을 기다리는 것이 좋습니다. 뭐라고 promise에 대한

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

읽기 $http이 그들을 사용하는 방법이다.

+0

덕분에, 내가 약속에 대해 읽고, 문제를 해결하기 위해 관리 : D – Erex

1

getArray 함수의 콜백으로 부울 값을 설정하거나 arrayValue에서 watch를 설정하고이를 기반으로 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가 비어 있지 않은 경우에도, 내가 두 번째 옵션을 시도,하지만 난 항상 빈 상태 (empty)의 배열이 ... 어떤 아이디어? – Erex

+0

제 편집이 효과가 있습니다. – Sharondio

+0

그것은 oldValue와 함께 작동하지만 그 후에도 항상 뒤쳐져 있습니다 : P 어떤 이유로 newValue는 항상 빈 배열을 반환합니다. / – Erex

관련 문제