修改作用域变量后,未更新作用域绑定

Scope binding is not getting updated after scope variable was modified

本文关键字:作用域 更新 绑定 变量 修改      更新时间:2023-11-28

在提交$Modal(modalInstance)时,我正在更新范围($scope.expense)上的数组,视图绑定到对象,datatable使用"expense"作为数据。我可以看到$scope.expense在调试时正在更新,并且正在插入一个新项,但在表中和{{expense.length}}绑定中,我看不到更新。我读过很多关于这个问题的问题,插入是在有角度的一侧执行的,所以如果我理解应用''摘要是不需要的。

我试过了:

  • 调用$scope$摘要''$scope$推送后的apply()(导致摘要已在进行中的错误)
  • 将push封装在$scope中的函数中$apply(函数)。相同错误,摘要已在进行中
  • 使用$timeout,这样推送将被推迟到下一个摘要周期-视图不会更新

上述选项均未解决问题。

视图(我确实看到了推送之前的长度,所以绑定在视图中定义正确,这就是为什么我不粘贴整个视图的原因):

<div class="row">
    <div class="ibox-content col-lg-10 col-lg-offset-1" ng-controller="LiveCtrl">
        {{expenses.length}}

        <div class="col-md-1" ng-controller="LiveCtrl">
            <button class="btn btn-link" ng-click="openAddExpenseModal()">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add Expense
            </button>
        </div>
    </div>
</div>

控制器代码,我推到支出新项目:

  modalInstance.result.then(function (newExpense) {
  ExpenseService.addExpense(newExpense).then(function (id) {
            console.log(id);
            $scope.expenses.push(newExpense);
        }, function (rejectData) {
            console.log(rejectData);
        });
    }, function (msg) {
        console.log('Modal dismissed at: ' + new Date() + 'Message - ' + msg);
    });

问题是您使用控制器两次,实际上创建了两个作用域,因此创建了两组数组:

这里一次:<div class="ibox-content col-lg-10 col-lg-offset-1" ng-controller="LiveCtrl">

第二次在这里:<div class="col-md-1" ng-controller="LiveCtrl">

因此,上面的一个显示了原始费用数组的长度,但实际上是在将费用添加到第二个控制器范围的数组中。父作用域中的原始作用域保持不变。

您需要做的是删除控制器的最后一个声明,创建:

<div class="row">
    <div class="ibox-content col-lg-10 col-lg-offset-1" ng-controller="LiveCtrl">
        {{expenses.length}}

        <div class="col-md-1">
            <button class="btn btn-link" ng-click="openAddExpenseModal()">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add Expense
            </button>
        </div>
    </div>
</div>