2016-11-23 110 views
0

我無法弄清楚爲什麼範圍變量沒有被分配。

<script src="https://js.paystack.co/v1/inline.js"></script> 
<button type="button" ng-click="checkout()">Checkout</button> 
<div ng-show='txref'> 
    <h2>Payment successful!</h2> Transaction reference: {{txref}} 
</div> 

JS

//this function triggers when the button above is clicked. Everything else except assigning the reference to $scope.txref 
$scope.checkout = function() { 
    var handler = PaystackPop.setup({ 
    key: 'pk_test_1c828c1b8d9a98232c90d7aa6c418953c8150096', 
    email: '[email protected]', 
    amount: 10000 * 100, 
    ref: Math.floor((Math.random() * 100000) + 1), 
    callback: function(response){ 
     console.log(response.reference) //works 
     alert(response.reference) //works 
     $scope.txref = response.reference; //doesn't work until you click the button again 
    }, 
    onClose: function(){ 
     alert('window closed'); 
     } 
    }); 
    handler.openIframe(); 
} 

回調一切正常,除了分配參考$ scope.txref。它拒絕工作,但是當你再次點擊按鈕時,一切都是正常的。我不知道什麼是錯的。

+0

初始化txref。 '$ scope.txref ='';' – taguenizy

回答

1

添加$scope.$apply()更新摘要。這應該可以解決您的問題。同時啓動對範圍變量:

$scope.checkout = function() { 
    $scope.txref = ''; 
    var handler = PaystackPop.setup({ 
    key: 'pk_test_1c828c1b8d9a98232c90d7aa6c418953c8150096', 
    email: '[email protected]', 
    amount: 10000 * 100, 
    ref: Math.floor((Math.random() * 100000) + 1), 
    callback: function(response){ 
     console.log(response.reference) //works 
     alert(response.reference) //works 
     $scope.txref = response.reference; 
     $scope.$apply(); // <---- This should do the work for you 
    }, 
    onClose: function(){ 
     alert('window closed'); 
     } 
    }); 
    handler.openIframe(); 
} 
+0

工作,謝謝! – iKey

+0

很高興我幫助;) –

-1

嘗試$timeout來包裝你的變量賦值例如,通知角有關的變化:

callback: function(response){ 
    console.log(response.reference) //works 
    alert(response.reference) //works 
    $timeout(function() { 
     $scope.txref = response.reference; //doesn't work until you click the button again 
    }); 
}, 

,不要忘記注入$超時到您的控制器,與$注入的方式相同

+1

這是一般不良做法。看看這篇不錯的文章:https://www.toptal.com/angular-js/top-18-most-common-angularjs-developer-mistakes –

+1

@VassilisPits,感謝您的支持,但請註明您的哪一部分在這篇文章中正在討論。由於我們在NG2中根本不會有* $ scope *,所以我個人認爲最好不要在控制器中使用* $ scope *,而是* controllerAs *和* this *。在這種情況下* $ timeout *是一個很好的解決方案。另外最好使用'$ scope。$ applyAsync'而不是'$ scope。$ apply' – Andriy

+0

檢查錯誤#8。此外,這個問題不是NG2,而是Angularjs 1.x.順便說一句,控制器(我也喜歡)與性能無關。祝你有美好的一天 –