动态更改ng个重复元素的宽度

Change width on ng-repeat elements dynamically

本文关键字:元素 ng 动态      更新时间:2023-09-26

我想通过调用一个函数来更改ng repeat的所有元素的宽度。这是我的HTML代码:

<div ng-controller="fillTab">
<table>
     <tr>
        <td ng-repeat="z in downLine" class="row">
           <table class="contUser" >
              <tr>
                <td>
                   <img src="{{z.picture}}" class='mask-pic'></img>
                   <p>Sometext</p>
                </td>
                <td>
                   <p>{{z.name}}</p>
               </td>
             </tr>
           </table>
         </td>  
     </tr>
</table>
</div>

"下线"是从工厂中提取的阵列。这个数组的长度是可变的

ejec = {
        "user0": {
            "name": "ejec0"
        },
        "user1": {
            "name": "ejec1"
        },
        "user2": {
            "name": "ejec2"
        }
}

因此,我需要的是一个函数,它可能在点击或定时器时,改变我每次调用ng时重复的所有class="row"元素的"宽度":

 $scope.changeWidth= function() {
   $scope.x = variableNumber;
    ng-repeatElements.width = x + "px"; ????
}

您想要使用ng样式,可以在此处找到文档。如果你在控制器中创建样式对象,你也可以有一个修改它的函数:

 $scope.rowWidth = {'width': '200px' };
 function setRowWidth(newWidth){
    $scope.rowWidth = {'width': newWidth + 'px' }
 }

然后你可以将ng样式添加到你的html 中

<td ng-repeat="z in downLine" ng-style="rowWidth">

只要范围变量rowWidth发生更改,视图就会根据角度渲染周期进行更新。

希望这能有所帮助!

使用ngClass:

$scope.changeWidth= function() {
   $scope.className = 'large';
}
<td ng-repeat="z in downLine" class="row" ng-class="className">

请参阅fiddle

我认为您可以在控制器中使用一个标志,并使用$timeout/$interval或控制器函数设置该类变量的新值。

见下文

var module = angular.module('myapp', []);
module.controller('controller', ['$scope', '$interval', function($scope, $interval){
      $scope.items = [
        {
            "name": "ejec0"
        },
        {
            "name": "ejec1"
        },
        {
            "name": "ejec2"
        }];
    $scope.class = 'base';
  
  $interval(function(){
    if($scope.class==='base') $scope.class='change';
    else $scope.class='base';
  }, 1000);
}]);
.base{with:50px; background-color:red;}
.change{with:150px; background-color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myapp">
  <head>
  </head>
  <body ng-controller="controller">
    <table>
      <tr ng-repeat="item in items" ng-class="class">
        <td ng-bind="item.name"></td>
        </tr>
      </table>
    </body>
</html>