我有一个像这样的结构(非常简化):
<div ng-controller="MainCtrl">
<div>Views and other stuff</div>
<div ng-controller="MyCtrl">
<div ng-repeat="item in $root.items track by $index">
{{item.id}}
</div>
<div>
Total value: {{totVal}}
</div>
</div>
</div>
在我的主 Controller 中,我定义了 $rootScope.items = [{id: 1,..},{id: 2,..},{id: 3,..},..] 并在我的我定义了 $scope.totVal = 0 的其他 Controller 和 items 数组的观察者,当 items 数组更改时更新 totVal ;
.controller('MainCtrl', ['$rootScope', '$scope', function($rootScope, $scope) {
// Are actually fetched from a service
$rootScope.items = [
{id: 1,..},
{id: 2,..},
..
];
}])
.controller('MyCtrl', ['$rootScope', '$scope', function($rootScope, $scope) {
$rootScope.updateTotVal = function() {
var totVal = 0;
// calculations are done here
// Is correct here when I console log after all calculations are complete
console.log(totVal);
$scope.totVal = totVal;
}
$scope.totVal = 0;
$rootScope.$watch('items', function() {
$rootScope.updateTotVal();
}, true);
}]);
我遇到的问题是 View 中的 totVal 没有更新。当我控制台记录该值时,它会在控制台中正确显示,但只有当我将 totVal div 滚动到 View 之外并再次返回时,它才会在 View 中更新。看起来像是 Chrome 中的 AngularJS bug,但当我 Google 时找不到任何类似的情况。它在 FireFox 中运行良好。
如果我在 ng-repeat 之前移动 totVal 它会起作用,如果我删除 ng-repeat 它会起作用(我宁愿不改变 html 的结构,因为这会做很多工作并使设计变得更糟)。我还尝试将 totVal 移至根范围,但没有成功。
这只是绘画/渲染失败,Batarang 和 console.log 总是给我更新的值。
有人遇到过这个问题吗?
最佳答案
我不知道这是否正是您想要的,因为我不知道您的用例。 但是,我实现了一个工作示例,请参见此处 codepen .
我对您的代码进行了一些重构,删除了额外的 Controller 并将 totVal
封装在服务中。另外,我使用 controllerAs
语法让一切变得更加清晰。
您的代码的问题在于 totVal
是一个原语。因此,当您为其分配新值时,Angular 将无法更新引用。这就是为什么您应该模型中始终有一个点!
看看我的代码,您会发现我将 totVal
声明为 var totVal = {val : 0}
。我只需更新 val
,保留引用并正确更新 View 。
.service('totVal', function(){
var totVal = {val:0};
this.computeTotVal = function(){
//perform computations, I will just increment
totVal.val++;
}
this.getTotVal = function() { return totVal; }
})
另请参阅 article .
关于javascript - ng-model 未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24553514/