在提交 $Modal (modalInstance) 时,我正在更新范围 ($scope.expenses) 上的数组, View 具有与对象的绑定(bind),数据表使用“expenses”作为数据。我可以看到 $scope.expenses 在调试时得到更新,并且正在插入一个新项目,但在表和 {{expenses.length}} 绑定(bind)中我看不到更新。我读过很多关于这个问题的问题,插入是在 Angular 一侧执行的,所以如果我理解 apply\digest 是不需要的。
我尝试过:
- 在推送后调用 $scope.$digest\$scope.$apply() (导致摘要已在进行中的错误)
- 将推送包装在 $scope.$apply(function) 中的函数中。同样的错误,摘要已在进行中
- 使用 $timeout 以便推送将被推迟到下一个摘要周期 - View 不会更新
上述选项均无法解决该问题。
View (我确实看到了推送之前的长度,因此在 View 中正确定义了绑定(bind),这就是为什么我不粘贴整个 View ):
<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>
我将新项目推送到费用的 Controller 代码:
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);
});
最佳答案
问题是您使用 Controller 两次,实际上创建了两个作用域,因此创建了两个数组:
到达这里:<div class="ibox-content col-lg-10 col-lg-offset-1" ng-controller="LiveCtrl">
第二次在这里:<div class="col-md-1" ng-controller="LiveCtrl">
所以上面的一个显示了原始费用数组的长度,但实际上您是将费用添加到第二个 Controller 作用域的数组中。父作用域中的原始值保持不变。
您需要做的是删除 Controller 的最后一个声明,创建:
<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>
关于javascript - 修改范围变量后,范围绑定(bind)未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28520015/