【问题标题】:ng-class dynamic doesn't change when resize window调整窗口大小时,ng-class 动态不会改变
【发布时间】:2016-05-16 17:21:13
【问题描述】:

我尝试了带有三元的 ng-class 指令,它在页面加载时效果很好。我的参考是widthWindow.xs变量,当窗口大小是移动时它是“true”,但是有一个resize把它设置为“false”但是类没有改变,ng-class没有动态改变。为什么?

在控制器中:

$scope.myResize = funcion(){
   var number = $window.innerWidth;
   if (number > 767) {
      $scope.widthWindow.xs = false;
   }else{
      $scope.widthWindow.xs = true;
   }
};

在html中:

<p ng-class="widthWindow.xs ? 'borderVoteNewsTop' : 'borderVoteNewsLeft'">Don't change when there is a resize</p>

【问题讨论】:

    标签: angularjs ternary-operator ng-class


    【解决方案1】:

    ngClass 指令的语法不正确。

    如下使用:

    <p 
      ng-class="{'borderVoteNewsTop': widthWindow.xs, 'borderVoteNewsLeft': !widthWindow.xs}"
    >
      Change when there is a resize
    </p>
    

    查看指令文档:https://docs.angularjs.org/api/ng/directive/ngClass

    【讨论】:

    • 这是另一种可能性,但现在使用 $scope.$apply() 可以完美运行。谢谢
    【解决方案2】:

    由于 'resize' 事件来自 Angular 框架之外,您需要将其操作与 AngularJS 摘要循环集成。使用$apply

    $scope.myResize = function(){
       var number = $window.innerWidth;
       if (number > 767) {
          $scope.$apply("widthWindow.xs = false");
       }else{
          $scope.$apply("widthWindow.xs = true");
       }
    };
    

    $apply 执行 Angular 表达式后,会自动调用一个摘要循环,ng-class 指令中的观察者会看到变化并更新类。

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 2021-04-06
      • 2012-07-29
      • 2019-06-17
      • 1970-01-01
      • 2017-03-25
      相关资源
      最近更新 更多