Javascript Angularjs在模型更新后不更新ng repeat的视图
我有一个“菜单指令”,当模型改变时,它拒绝更新html视图中的项目。我使用angular js和for-each语句。 这是我精简到的最低代码 该指令:Javascript Angularjs在模型更新后不更新ng repeat的视图,javascript,angularjs,Javascript,Angularjs,我有一个“菜单指令”,当模型改变时,它拒绝更新html视图中的项目。我使用angular js和for-each语句。 这是我精简到的最低代码 该指令: export function SideNavbarDirective() { 'ngInject'; let directive = { restrict: 'E', templateUrl: 'app/components/sideNavbar/sideNavbar.html',
export function SideNavbarDirective() {
'ngInject';
let directive = {
restrict: 'E',
templateUrl: 'app/components/sideNavbar/sideNavbar.html',
scope: {
},
controller: SideNavbarController,
controllerAs: 'vm',
bindToController: true
};
return directive;
}
class SideNavbarController {
constructor($scope, $timeout) {
'ngInject';
$scope.myItems = [
{
displayName:"1",
highlight:true,
},
{
displayName: "2",
highlight: false,
},
{
displayName: "3",
highlight: false,
},
];
$timeout(() => {
$scope.myItems[0].highlight = false;
$scope.myItems[1].highlight = true;
$scope.myItems.length = 2;
$scope.$apply()
}, 4000);
}
}
html:
<div ng-repeat="item in myItems" layout="row">
<div flex layout="column">
<div layout="row">
<span>{{item.displayName | translate}}</span><span flex=""></span><span ng-show="{{item.highlight}}">*</span>
</div>
</div>
</div>
计时器后:
1*
2
1
2*
1 false
2 true
计时器后的预期结果:
1*
2
1
2*
1 false
2 true
正如您所能看到的那样,删除项目会反映出来。但是改变数组中对象的内容会被angular忽略。我做错了什么
编辑:
我更新了HTML,只打印highlight属性的值
<div ng-repeat="item in myItems" layout="row">
<div flex layout="column">
<div layout="row">
<span>{{item.displayName | translate}}</span><span flex=""></span><span>{{item.highlight}}</span>
</div>
</div>
</div>
计时器后:
1*
2
1
2*
1 false
2 true
现在我得到了期望值。世界跆拳道联盟!
问题一定出在ng show表达式上,还是什么?我比以往任何时候都更困惑。在
ng show
中不需要大括号,因此它应该是ng show=“item.highlight”
尝试按$scope查看数组中的更改。$watch一旦数组更改,指令必须通过添加$scope来获得最新的更改。$apply来反映更改。嗯,在绝望中,我确实在超时函数中最后添加了$scope.$apply(),正如您在示例中看到的那样。但这没有任何区别。也。我不认为这应该是必要的,因为$timeout无论如何都应该触发apply,是的。现在它工作得很好。这几乎令人尴尬:)