AngularJS:由于服务的异步性质,函数的计算结果总是为false

AngularJS: function always evaluates to false because of Async nature of service

本文关键字:计算 函数 结果 false 异步 于服务 AngularJS 服务      更新时间:2023-09-26

我的模板看起来像

<div data-ng-if="budgetSummaryExists()">
        <span>You have not budget</span>
        <button type="button" class="btn btn-danger"
                data-ng-click="setRoute('budgets')">Create
            Budget
        </button>
    </div>
    <div data-ng-if="$scope.budgetSummaryExists">
        <span>your budget summary exists</span>
    </div>

我的控制器看起来像

function BudgetSummaryController($scope, $location, BudgetSummary) {
    /* For default view when budgets is clicked */
    $scope.thisMonthBudgetSummary = function () {
        console.log('retrieving budget summary');
        var date = new Date();
        BudgetSummary.get({'month': date.getMonth() + 1, 'year': date.getFullYear()},
            function (data) {
                $scope.budgetSummary = data;
                // success
                console.log('budgetSummary:', data);
            },
            function (error) {
                //error
                console.log('error:', error.status);
            })
        ;
    };
    $scope.budgetSummaryExists = function () {
        return $scope.budgetSummary !== undefined;
    }

问题
-即使在服务返回数据budgetSummaryExists()评估为false之前,我也看不到DOM 的其他部分

问题

如何确保函数budgetSummaryExists()仅在服务完成从服务器获取数据时进行评估?

我的模板错误,这修复了

    <div data-ng-if="! budgetSummaryExists()">
        <span>You have not budget</span>
        <button type="button" class="btn btn-danger"
                data-ng-click="setRoute('budgets')">Create
            Budget
        </button>
    </div>
    <div data-ng-if="budgetSummaryExists()">
        <span>your budget summary exists</span>
    </div>