I have an Angularjs sample snippet. here using ng-repeat directive to display names in a table, I am planning to add ng-style directive to add vertical scroll bar to a table based on table row count. how can i make below code to work?
Eg: we need vertical scroll bar to a table only if the count of table rows is more than 4 I tried like this
<div ng-if= "names.length > 4" ng-style="{'overflow-y': 'auto'}" >
<table>
---------
</table>
</div>
Please help by correcting the code
Here is sample code
<!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>
Use ngStyle. It would likely be best to apply the (ng-)style to an element that contains the table. Set a height attribute (e.g. 100px). Then the overflow-y style will cause any content beyond that threshold to be added in the scrolling area.
<div ng-style="containerStyle">
<table>
<!--table rows-->
</table>
</div>
See this working the sample below.
Note: I changed the AJAX call to an endpoint from the StackExchange API, so as to avoid CORS issues.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With