2017-02-17 54 views
0

我有一個Angular組件(即時使用v1.5.6),它偵聽設備方向,然後在用戶使用平板電腦並轉向肖像時顯示消息模式(對此的檢查工作正常)。我的模板是:當使用addEventListener觸發屬性時,角度組件不會重新呈現

<div ng-show="$crtl.isTablet" class="orientation-warning-message tablet-warning-message"> 
    <p>We think you are accessing this app on a tablet - you must use the app in landscape mode to continue (turn on side)</p> 
</div> 

和我的組件:

angular 
    .module('myApp') 
    .component('checkDevice', { 
    templateUrl: 'directives/checkDevice/checkDevice.tpl.html', 
    controller: function() { 
     var self = this; 

     this.isTablet = false; 

     window.addEventListener("orientationchange", function() { 

     // do some checks here and if a tablet and on portrait mode then: 
     self.isTablet = true; 

     }, false); 

    } 
}); 

但該消息沒有顯示,因爲從addEventListener回調中設置isTablet不會出現重新渲染的成分。如果我在addEventListener回調之外設置了isTablettrue,那麼它起作用。我是否需要手動觸發組件重新渲染?

回答

1

你有沒有嘗試添加$範圍$適用()......像:

angular 
    .module('myApp') 
    .component('checkDevice', { 
    templateUrl: 'directives/checkDevice/checkDevice.tpl.html', 
    controller: function(scope) { 
     var self = this; 

     this.isTablet = false; 

     window.addEventListener("orientationchange", function() { 


     // do some checks here and if a tablet and on portrait mode then: 
    scope.$apply(function(){  
     self.isTablet = true; 
    }); 
     }, false); 

    } 
}); 

原因角看不到外部事件(如的setTimeout()),你必須迫使它刷新您的範圍

+0

該作品謝謝! – Mark

+0

很高興幫助你! –

相關問題