2016-11-23 10 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 
    }); 
}, 

をし、あなたに$タイムアウトを注入することを忘れないでくださいコントローラは、$ scopeと同じ方法で注入されます。

+1

この一般的な悪い習慣です。この素敵な記事をご覧ください:https://www.toptal.com/angular-js/top-18-most-common-angularjs-developer-mistakes –

+1

@VassilisPits、ありがとうございますが、この記事では話しています。 * $ scope *はNG2にはまったくないので、私は個人的には$ scope *を使用しないほうがよいと思いますが、コントローラー内のcontrollerAs *と* this *を使用するほうがずっと良いと思います。この場合、* $ timeout *は良い解決策です。また、 '$ scope。$ applyAsync'ではなく' $ scope。$ apply'を使用する方が良いでしょう。 – Andriy

+0

間違いを確認してください。また、この質問はNG2ではなく、Angularjs 1.x。 BtwまたcontrollerAss(私も好む)パフォーマンスとは何の関係もありません。良い日をお持ちなさい –

関連する問題