【问题标题】:Run code in scope first after Factory method is finished in AngularJS在 AngularJS 中完成工厂方法后首先在范围内运行代码
【发布时间】:2013-10-24 16:00:54
【问题描述】:

这是我的工厂代码:

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 &lt;= 0) 在$scope.arrayValue 得到它的值形式$simpleFactory.getArray($scope.searchWord) 之前执行。
所以我的问题是我如何才能等到 getArray 函数完成才能触发我的代码:

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

【问题讨论】:

    标签: angularjs wait factory promise deferred


    【解决方案1】:

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

    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 如何使用它们。

    【讨论】:

    • 谢谢,我阅读了有关承诺的内容,并设法解决了问题:D
    【解决方案2】:

    您可以将布尔值设置为 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);
        });
    
     };
    

    【讨论】:

    • 我尝试了第二个选项,但我总是得到一个空数组,即使 arrayValue 不为空......有什么想法吗?
    • 它与 oldValue 一起工作,但它明显落后了一步:P 出于某种原因,newValue 总是返回一个空数组:/
    猜你喜欢
    • 2014-01-22
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多