我有一個「菜單指令」,當模型更改時拒絕更新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