Reputation: 797
I'm trying to detect when mobile media queries are activated on my page. To do so, I'm using a "phantom" div.
<div class="mobile-alert" mobile-mode></div>
The class .mobile-alert
is set display:none
when mobile media queries are activated and display: block
when they aren't. Now I use the following directive:
.directive('mobileMode', ["shareProperties", function(shareProperties){
return{
link: function(scope, elem, attrs){
var mobileSize;
$(window).resize(function(){
var mobileSize = $(elem).is(':visible');
shareProperties.setMobileSize(mobileSize);
});
}
}
}])
It watches if this div is visible, and with that I know if page is on mobile mode or not. Then, on shareProperties service:
.factory("shareProperties", function(){
var properties = {mobileSize: false};
return {
getMobileSize: function(){
return properties.mobileSize;
},
setMobileSize: function(value){
properties.mobileSize = value;
console.log(this.getMobileSize());
}
};
})
I share this variable with some controllers. However, the variables are set inside this service, but when I try to use them on a controller, like ctrl.mobileMode = shareProperties.getMobileSize;
, calling this function on HTML with {{ctrl.mobileMode()}}
always displays false. Any ideas ?
Upvotes: 1
Views: 38
Reputation: 28750
.directive('mobileMode', ["shareProperties", function(shareProperties){
return{
link: function(scope, elem, attrs){
var mobileSize;
$(window).resize(function(){
var mobileSize = $(elem).is(':visible');
shareProperties.setMobileSize(mobileSize);
scope.$apply();
});
}
}
}])
You've done something outside of angular by listening on the $(window).resize
event, because of this you have to tell angular hey angular! update yourself
. You can achieve this by running the scope.$apply()
above.
Upvotes: 1