如何根据'ng-repeat'计数分配'ng-style'指令值



i有一个gangularjs样品片段。在此,使用NG重复指令在表中显示名称,我计划添加NG风格的指令,以根据表行计数将垂直滚动条添加到表中。如何在下面的代码下工作?

eg:我们只有在表行超过4时才需要垂直滚动条才能到表我尝试了这样的

<div ng-if= "names.length > 4" ng-style="{'overflow-y': 'auto'}" >
      <table>
        ---------
      </table>
</div>

请纠正代码

请提供帮助

这是示例代码

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl"> 
<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>
</div> 
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .then(function (response) {$scope.names = response.data.records;});
});
</script>
</body>
</html>

使用ngstyle。最好将(NG-)样式应用于包含表的元素。设置A 高度属性(例如 100px )。那么溢出Y 样式将导致在滚动区域中添加超出该阈值的任何内容。

<div ng-style="containerStyle">
   <table>
    <!--table rows-->
   </table>
</div>

请参阅下面的样本。

注意:我将Ajax调用从Stackexchange API更改为端点,以避免CORS问题。

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
  $scope.containerStyle = {
    border: '3px solid #f0f0f0',
    'max-height': '100px'
  };
  $http.get("https://api.stackexchange.com/2.2/users?key=U4DMV*8nvpm3EOpvf69Rxw((&site=stackoverflow&pagesize=10&order=desc&sort=reputation&filter=default")
    .then(function(response) {
      $scope.names = response.data.items;
      if ($scope.names.length > 4) {
        $scope.containerStyle['overflow-y'] = 'auto'; // max-height: 30px;';
      }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
  <div ng-style="containerStyle">
    <table>
      <tr ng-repeat="x in names">
        <td>{{ x.display_name }}</td>
        <td>{{ x.location }}</td>
      </tr>
    </table>
  </div>
</div>

选择该表应该使用哪种样式,您可以使用三元运算符选择一组样式。

<div ng-style="(names.length > 4 ? {'overflow-y': 'scroll'} : {'overflow-y': 'auto'})" 
     style="height: 50px;">
  <table>
    ...
  </table>
</div>

我建议,如果您的样式变得复杂了,则应使用ngClass指令在满足条件的情况下应用类,然后定义要应用于样式表或style标签的样式。这将使我认为代码更容易阅读。

<table ng-class="{'scrollable': names.length > 4}">
    <tr ng-repeat="x in names">
        <td>{{ x.Name }}</td>
        <td>{{ x.Country }}</td>
    </tr>
</table>
<style>
    table { 
        overflow-y: auto;
        display: block;
    }
    .scrollable {
        overflow-y: scroll;
    }
<style>

最新更新