AngularJS:由于服务的异步性质,函数总是求值为false

时间:2014-04-20 16:20:59

标签: javascript angularjs angularjs-scope angularjs-service

我的模板看起来像

<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()仅在服务从服务器获取数据时评估?

1 个答案:

答案 0 :(得分:0)

我的模板错了,这解决了它

    <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>