我遇到了ng-class的问题。
这是我的控制器
的一部分export class UIController
{
public static $inject = [];
public commands: Array<string> = ['showMap', 'showGantry', 'showSign'];
public showMap: boolean = false;
public showGantry: boolean = false;
public showSign: boolean = false;
public loadingMessage: string;
constructor()
{
this.showMap = true;
}
public toggleContent(commandToExecute: string)
{
for (var command of this.commands) {
if (command != commandToExecute) {
this[command] = false;
}
else if (!this[command]) {
this[command] = true;
}
}
}
}
与之相关的指令
class LeafletMap implements ng.IDirective
{
public restrict: string = "A";
public controller: string = 'UIController';
public link = (scope, elem, attr) : void =>
{
scope.uiCtrl.loadingMessage = 'test';
scope.$root.$on('details', (event: IAngularEvent, message: any) =>
{
scope.uiCtrl.toggleContent('showGantry');
});
};
}
和HTML视图:
<div class="accordion-button" data-ng-click="uiCtrl.toggleContent('showGantry')">Gantry</div>
<div class="accordion-content" data-ng-class="{'show-content':uiCtrl.showGantry}">test</div>
当我通过toggleContent
调用ng-click
方法时,一切正常。
但是当调用来自LeafletMap directive
时,它会运行toggleContent
方法,并在UIController
中为公共属性设置正确的布尔值,但ng-class
不会更新。
scope.uiCtrl.loadingMessage = 'test'; //it works correctly BTW
当我在调用scope.$apply()
方法后在LeafletMap
内运行toggleContent
(仅用于测试)时,ng-class已更新,但当然会导致apply already in progress
之类的错误
当我在指令中调用适当的控制器方法时,为什么ng-class
不会更新?
scope.$root.$on('gantry-details', (event: IAngularEvent, message: any) =>
{
this._timeout(() =>
{
scope.uiCtrl.toggleContent('showGantry');
});
});
使用timeout
解决了问题。