我正在尝试根据屏幕的宽度和测试变量隐藏元素。我遇到了一种极端情况,即ng-if指令尽管值是false仍不能正确隐藏元素。以下是相关的代码段。控制台日志报告我的要素应该是可见的,但是没有显示出来。

$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>

最佳答案

您的问题是jQuery事件是在Angular摘要周期之外触发的,因此您需要手动调用$scope.$apply

$(window).load(jqCheckWindowSize);
$(window).resize(jqCheckWindowSize);

function jqCheckWindowSize() {
  $scope.$apply($scope.checkWindowSize);
}

或以 super 用户两行的方式:
$(window).load  ($scope.$apply.bind($scope, $scope.checkWindowSize));
$(window).resize($scope.$apply.bind($scope, $scope.checkWindowSize));

或者,您可以直接在$scope.$apply中调用checkWindowSize或使用$timeout等包装代码。此处的许多答案已经涵盖了这一点。

10-02 13:10