【问题标题】:How do I change ng-class on window resize?如何在窗口调整大小时更改 ng-class?
【发布时间】:2016-08-03 14:00:53
【问题描述】:

我有一个功能,当我将屏幕缩小到某个尺寸以下并单击表格行时,它会显示该表格行中的其他项目。 (左侧的白屏)。

然后,当我展开窗口时,我希望所有表格行恢复正常,但我有一个错误,如果它已经打开,它不会关闭。

我尝试将 $scope.showIt 变量设置为 true/false,但它似乎只有与初始 $scope.showIt 值相反时才会产生效果。当屏幕为一定大小时,如何更改每个 td 中的所有 ng-classes?

这是我的html:

<tr class="table-body  "ng-repeat="service in services | orderBy:myOrderBy | filter:search">
    <td align="center" valign="middle" ng-click="showIt = dropDetails(showIt)" ng-class="{'name-show':showIt, 'name-show-disabled':!showIt}">{{ service.name }}</td>
    <td  ng-class="{'show':showIt, 'show-disabled':!showIt}">{{ service.description }}</td>
    <td  ng-class="{'show':showIt, 'show-disabled':!showIt}">{{ service.prices }}</td>
</tr>

在我的控制器中:

$scope.dropDetails = function(showIt){ //This function works well. 
    console.log(window)     
    console.log(window.innerWidth)      
    if(window.innerWidth < 760){
        return !showIt;
    }else{
        return showIt;
    }

}

var w = angular.element($window);
var resizeId=0; 
$scope.showIt = true;

w.bind('resize ', function (a) {
        clearTimeout(resizeId);
        resizeId = setTimeout(function(){

        if(w[0].innerWidth < 760){

        }else{

            $scope.showIt = true;  //Does nothing. 
            $scope.$apply();

        }                   
        }, 500);
})

【问题讨论】:

  • 您从未将$scope.showIt 设置为false。是错字吗?
  • @AdnanUmer dropDetails 函数在 ng-click 时将其设置为 false
  • if(window.innerWidth &lt; 760){ return !showIt; }
  • 窗口再次变大后如何重新设置变量“w”?
  • w[0].innerWidth 准确调整窗口大小。

标签: css angularjs ng-class


【解决方案1】:

在 Angular 视图中定义 ng-model 时,请务必使用 Dot Rule。因此,这将帮助您在引用那里的属性时遵循原型继承。

这里的原因是,您使用了ng-repeat(它确实会在每次呈现模板时创建原型继承的子范围)。在这里你需要做同样的事情。定义像 $scope.model 这样的模型,并在其中定义 showIt 属性。相反,您应该将showIt 放在services 的每个元素上,通过它您可以单独处理每个事件。

标记

<tr class="table-body" ng-repeat="service in services | orderBy:myOrderBy | filter:search">
    <td align="center" valign="middle" 
      ng-click="service.showIt= dropDetails(service.showIt)" 
      ng-class="{'name-show':service.showIt, 'name-show-disabled':!service.showIt}">
        {{ service.name }}
    </td>
    <td  ng-class="{'show':service.showIt, 'show-disabled':!service.showIt}">
       {{ service.description }}
    </td>
    <td  ng-class="{'show':service.showIt, 'show-disabled':!service.showIt}">
        {{ service.prices }}
    </td>
</tr>

现在的问题仍然是如何隐藏所有services,这样就很容易了。循环遍历每个 services 集合元素并将 showIt 变量设为 false。

angular.forEach($scope.services, function(service){
   service.showIt = false;
})

另外,您在 DOM 上使用自定义事件,我建议您将此代码放入指令中。这样也可以重复使用。

【讨论】:

  • 谢谢,它适用于调整大小,但现在当我点击任何一个时,它们都会显示。我需要在点击时单独设置它们,然后在调整大小时将它们全部隐藏。
  • @Squirrl 很高兴为您提供帮助。谢谢:-)
猜你喜欢
  • 2016-05-16
  • 1970-01-01
  • 2016-07-07
  • 2013-09-17
  • 2016-07-08
  • 2011-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多