我有一个Angular组件(我使用v1.5.6),它监听设备方向,然后在用户使用平板电脑并且已经转为纵向模式时显示一条消息(对此的检查工作正常)。我的模板是:
<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);
}
});
但是消息没有显示,因为在isTablet
回调中设置addEventListener
似乎不会重新呈现组件。如果我在isTablet
回调之外设置true
到addEventListener
,那么它就可以了。我是否需要以某种方式手动触发组件重新渲染?
答案 0 :(得分:1)
您是否尝试添加$ scope。$ apply()... like:
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);
}
});
原因Angular看不到外部事件(比如SetTimeOut())你必须强制它刷新你的范围