我有一个“菜单指令”,当模型更改时拒绝更新html视图中的项目。我用for-each语句使用角度js。 这是我已经剥离的最小代码。Angularjs在模型更新后没有更新ng-repeat的视图
的指令:
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
3
定时器后:
1*
2
计时器后
预期结果:
1
2*
,你可以删除本身的项目反映。但是改变数组中对象的内容却不会被角度注意到。我究竟做错了什么?
编辑: 我更新了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>{{item.highlight}}</span>
</div>
</div>
</div>
现在,我得到: 初始视图:
1 true
2 false
3 false
定时器后:
1 false
2 true
所以,现在我得到的预期值。 WTF! 问题必须与ng-show表达式或什么?我比以往更困惑。
尝试通过$ scope。$ watch监视数组中的更改,并且只要数组更改,该指令必须通过添加$ scope来具有最新更改; $ apply用于反映更改。 –
嗯,无奈之下,我确实放了一个$ scope。$ apply()在超时函数中最后一个,就像你在例子中看到的那样。但是这没有什么区别。也。我不认为这是应该需要的,因为$超时应该触发应用 – tkarls