angularjs – 无法完全访问条带回调中的$scope变量?

前端之家收集整理的这篇文章主要介绍了angularjs – 无法完全访问条带回调中的$scope变量?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将条纹集成到一个角度项目中.我正在我的控制器中运行条带方法,我想从回调更新各种范围值.我相信有一些范围问题我不理解.我可以在回调中控制记录我的范围变量,再次更新它们和控制台日志以查看新值.但是,如果我尝试在回调之外再次记录变量,我会得到旧值,然后新值不会进入我的视图.我也试过将我的$scope基元移动到$scope对象无济于事.这是一个例子.
app.controller('checkoutCtrl',function ($scope) {

    // default values
    $scope.receipt = {};
    $scope.paymentSuccess = false;
    $scope.saveCardForFuture = true;

    Stripe.card.createToken($scope.card,function (status,res) {

        $scope.receipt = res.data;
        $scope.paymentSuccess = true;

        if ($scope.saveCardForFuture === true) {
            // save card token
        }

        // tests cases
        console.log($scope.saveCard)       //logs undefined
        console.log($scope.receipt)        //logs the response data
        console.log($scope.paymentSuccess) //logs true 
    });

    // timeout long enough to wait for stripe response
    $timeout(function() {
        console.log($scope.receipt);       //logs {}
        console.log($scope.paymentSuccess) //logs false
    },1000);

});

注意:Stripe不作为控制器依赖项传递,我只是从我的html索引页面全局包含它.我还没有找到一种方法将其作为可注射依赖项包含在内,但必须有更好的方法.

你在条带回调中留下了angularjs世界.用$scope封闭回调块.$apply(fn);

一些好的阅读:http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

app.controller('checkoutCtrl',res) {
        $scope.$apply(function () {
            $scope.receipt = res.data;
            $scope.paymentSuccess = true;

            if ($scope.saveCardForFuture === true) {
                // save card token
            }

            // tests cases
            console.log($scope.saveCard)       //logs undefined
            console.log($scope.receipt)        //logs the response data
            console.log($scope.paymentSuccess) //logs true 
        });
    });

    // timeout long enough to wait for stripe response
    $timeout(function() {
        console.log($scope.receipt);       //logs {}
        console.log($scope.paymentSuccess) //logs false
    },1000);

});
原文链接:https://www.f2er.com/angularjs/240412.html

猜你在找的Angularjs相关文章