AngularJS ng-class没有更新

时间:2016-11-15 18:05:40

标签: javascript angularjs angularjs-scope

我遇到了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解决了问题。

0 个答案:

没有答案