【问题标题】:how to call a asynchronous function in the html for angularjs如何在 html 中为 angularjs 调用异步函数
【发布时间】:2016-05-25 03:33:33
【问题描述】:

我正在调用一个函数 df(stuff, morestuff),它从 html 中的 firebase 返回数据。但是该函数最终没有返回任何数据,因为 df 它是一个异步函数。怎么办??

<div>{{ df(stuff, morestuff) }}</div>


$scope.df = function(stuff, morestuff){
    ref.child(stuff).child(morestuff).once('value', function(dataSnap){
        return dataSnap.val();
    })
}

非常感谢您的帮助。

【问题讨论】:

    标签: javascript angularjs asynchronous firebase firebase-realtime-database


    【解决方案1】:

    您不能返回尚未加载的数据。解决方案是将您的代码改写为“加载数据后,执行...”。

    function(stuff, morestuff){
        ref.child(stuff).child(morestuff).once('value', $timeout(function(dataSnap){
            $scope.df = dataSnap.val();
        }));
    }
    

    这样做的好处是,它甚至可以在您使用 on()(而不是 once())时工作,并且在这种情况下会在数据更新时自动更新 AngularJS 视图。

    【讨论】:

    • 谢谢弗兰克。我以前使用过该技术,但我在嵌套的 ng-repeat 中多次调用该函数。我可以做一个范围对象并填写值,我只是希望能从函数中获取返回值。
    • 不幸的是,这是不可能的。它是异步加载的,浏览器不能(也不应该)等待数据返回。
    【解决方案2】:

    这很简单,你对某个变量进行绑定,然后在控制器中用你想要的任何东西填充这个变量。

    HTML:

    <div>{{variable}}</div>
    

    控制器:

    app.controller('appCtrl', ['$scope', function ($scope) {
        ref.child(stuff).child(morestuff).once('value', function(dataSnap){
            $scope.variable = dataSnap
            //  Verify if angular isn't digesting already (procesing changes)
            if(!$scope.$$phase) {
                //  Angular ain't aware of changes, so we make it do it's cycle.
                $scope.$apply()
            }
        })
    }])
    

    【讨论】:

    • 感谢 Akxe,请参阅上面对 Frank 的评论。
    猜你喜欢
    • 2020-03-09
    • 2020-12-20
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2018-10-03
    • 1970-01-01
    相关资源
    最近更新 更多