2017-11-25 187 views
2

我是angularjs中的新成員,並且作爲啓動器,我在訪問外部對象然後函數時遇到問題。我創建了一個工廠:如何在angularjs中承諾函數外訪問對象

var injectParams = ['$http']; 
    var address = function ($http) { 
    var factory = {}; 

    factory.get = function() { 
     return $http({ 
      method: "POST", 
      url: '/address', 
      headers: { 
       'Content-Type': 'application/json' 
      }, 
      data: { 
       service: 'address' 
      } 
     }); 
    }; 
    return factory; 
} 

和控制器方法:

function getAddresses() { 
     address_factory.get().then(function success(response) { 
      $scope.billing = response.data.billing; 
      $scope.shipping = response.data.shipping; 
      console.log(response.data); 

     }, function error(x) { 
      console.log(x); 
     }); 
    } 
    getAddresses(); 

的問題是如何訪問外getAddresses功能$scope.billing對象?我已閱讀angularjs承諾,但我不知道如何使用......

回答

1

$scope.billing無處不在控制器和綁定到該控制器的模板。但$scope.billing的值是動態的,它是undefined,直到factory-get Promise得到解決。爲了反映$scope.billing在模板中的動態特性,你可以嘗試以下方法:

function getAddresses() { 
    $scope.loading = true; 
    address_factory.get().then(function success(response) { 
     $scope.billing = response.data.billing; 
     $scope.loading = false; 
     $scope.error = null; 
    }, function error() { 
     $scope.loading = false; 
     $scope.error = true; 
    }); 
    } 
getAddresses(); 

,然後在模板:

<div ng-if="loading"> 
    Loading... 
</div> 
<div ng-if="!loading && error"> 
    Got an error! 
</div> 
<div ng-if="!loading && !error"> 
    Billing: {{billing}} 
</div> 

此外,您還可以使用$scope.$watch在控制器觀看for $scope.billing changes:

// ... 
getAddresses(); 

$scope.$watch('billing', function() { 
    // $scope.billing has been changed 
    console.log($scope.billing); 
}); 

但我會建議在Promise.then調用的成功回調中做好所有必要的邏輯。

+0

是的,你是對的。我理解這種情況發生的原因。你有任何模式建議如何解決它。'要解決它'我的意思是如何使用成功回調內部必要的邏輯? –

+0

@MrAlb沒有什麼可以解決的,這就是Promise的工作原理,所以只需將你的邏輯放在watch-callback或者'address_factory.get'成功回調中(我寧願選擇第二個選項)。另外,如果您對ES2017可以使用,您可以嘗試[異步等待](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)語法以使代碼更加完善同步等。 – dhilt

+0

也許我不會解釋得很好。我已經在同一個controller中創建了另一個分頁函數.Idea是,我想找到$ scope.billing對象的這個長度,所以我可以在分頁函數中使用。我瞭解promise是如何工作的但如果沒有找到這個對象的長度,我不能做分頁。我很抱歉,我花了你的時間。 –

2

$範圍變量可outse承諾在控制器曾經無處不在...

因此$ scope.billing將訪問在html和控制器js都...

+0

這是什麼意思...'因此$ scope.billing將可以通過html和控制器js訪問'?當我嘗試輸出$ scope.billing或在getAddresses函數外部查找此對象的長度時,結果爲空。的console.log($ scope.billing);我的意思是我知道在HTML我可以訪問對象,但想訪問控制器。 –

+1

這是因爲承諾是在事件循環中,你在事件循環返回之前訪問..嘗試在$ timeout – Danish

+1

@Danish中使用它不,**不使用'$ timeout' **。當值可用時,使用promise上的'then'回調來運行代碼。 – Bergi

0

$範圍意味着目前的範圍,它是當前區域,其中一些-controller.js &的一些-view.html訪問。

如果設置爲$範圍任何變量將是您隨時隨地訪問在一些-controller.js &一些-view.html。

假設您將ng-controller設置爲<div ng-controller="SomeController">.....</div>。因此,在$ scope.something中設置$ scope的任何東西都可以在控制器中訪問,並且也可以使用這個div,因爲控制器的範圍就是這個。