Ng-如果在观察变量变为false时不隐藏元素

时间:2015-05-05 23:59:31

标签: javascript jquery angularjs

我试图根据屏幕宽度和测试变量隐藏元素。我遇到了一个边缘情况,即使值为false,ng-if指令也没有正确隐藏元素。以下是相关的代码段。控制台日志报告我的元素应该是可见的,但它没有显示出来。

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

1 个答案:

答案 0 :(得分:2)

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

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

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

或者在poweruser中以两行方式:

$(window).load  ($scope.$apply.bind($scope, $scope.checkWindowSize));
$(window).resize($scope.$apply.bind($scope, $scope.checkWindowSize));

或者,您可以直接在$scope.$apply中致电checkWindowSize或使用$timeout等包装代码。此处的许多答案已涵盖此内容。