在AngularJS中完成Factory方法之后,首先在范围中运行代码

时间:2013-10-16 13:43:36

标签: angularjs wait factory promise deferred

所以这是我的工厂代码:

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

2 个答案:

答案 0 :(得分:1)

首先从工厂方法promise返回getArray

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

     factory.getArray = function (srchWord) {

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

    return factory;
});

其次等待使用then解决的承诺。

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

了解promise是什么,$http如何使用它们。

答案 1 :(得分: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);
    });

 };