Ng - if not hide element when observable turns to false
I am trying to hide an element based on screen width and test variable. I am running into an edge case where the ng-if directive is not hiding an element despite being false. Here are the relevant code snippets. The console log says my item should be visible, however it is not showing.
$scope.setContents = function(contents) {
$scope.noteContent=contents;
$scope.noteVisible=true;
$scope.hideNoteList();
}
$scope.checkWindowSize = function() {
if ( $(window).innerWidth() < 768 ) {
$scope.smallScreen = true;
console.log("Window size is small");
$scope.hideNoteList();
}
else {
$scope.smallScreen = false;
console.log("Window size is not small");
$scope.hideNoteList();
}
}
$scope.hideNoteList = function () {
if($scope.smallScreen && $scope.noteVisible){
$scope.noteListVisible= false;
console.log("Note List Should be Hiding");
}
else {
console.log("Note List Should be Visible");
$scope.noteListVisible= true;
}
}
$(window).load($scope.checkWindowSize);
$(window).resize($scope.checkWindowSize);
Html
<ul class="list-group col-xs-0 col-sm-6 col-md-4 col-lg-3" ng-if="noteListVisible">
<li ng-repeat="note in notes>
<h2 ng-click="setContents(note.content)"></h2>
</li>
source to share
Your problem is that jQuery events are fired outside of the Angular digest loop, so you need to call it $scope.$apply
manually.
$(window).load(jqCheckWindowSize);
$(window).resize(jqCheckWindowSize);
function jqCheckWindowSize() {
$scope.$apply($scope.checkWindowSize);
}
Or in poweruser mode with two lines:
$(window).load ($scope.$apply.bind($scope, $scope.checkWindowSize));
$(window).resize($scope.$apply.bind($scope, $scope.checkWindowSize));
Alternatively, you can call $scope.$apply
directly in, checkWindowSize
or wrap the code with $timeout
, etc. Many of the answers here already cover this.
source to share