Tips for setting the value of the 'ng-style' directive depending on the number of times 'ng-repeat' is repeated

I am working on an AngularJS project with a sample snippet that uses the ng-repeat directive to display names in a table. I want to add the ng-style directive to include a vertical scroll bar in the table based on the number of rows. How can I modify the code below to achieve this functionality?

For example, I only want the table to have a vertical scroll bar if there are more than 4 rows.

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

Please assist me in correcting the code above.

Here is the original 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> 

<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>

Answer №1

To achieve this, you can utilize the ngStyle directive in AngularJS. It is recommended to apply the styling to a container element that wraps around the table. You can set a specific height attribute (e.g. 100px) on this container and use the overflow-y property to enable scrolling when the content exceeds this height.

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

You can see this functionality in action in the example below.

Please Note: I have updated the AJAX call to use an endpoint from the StackExchange API to avoid any 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>

Answer №2

If you need to decide which set of styles should be applied to the table, you can utilize a ternary operator for this purpose.

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

For more complex styles, it is recommended to use the ngClass directive to add a class based on a condition and then define the styles in a stylesheet or inline style tag. This approach enhances code readability in my view.

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adding a removal icon to the top corner of an uploaded image

https://i.sstatic.net/eztiy.png <div *ngFor="let selected of base64textString;let index = index"> <img [src]="selected.imageString" style="height: 100px; width:100px;"> <i class="ft-trash-2 da ...

Switch between clicking and hiding

I am currently working on data tables and have successfully loaded my table via ajax, which also populates a new row drop down. However, I am experiencing an issue where I can get the row to drop down but cannot get it to close again. It simply adds the ...

Guide on adding a personalized table or Div section in a datatable

I am looking to add a custom table above a datatable, specifically I want the custom table to be displayed above the header columns. Here is the code I have tried: columns: [ { "data": "WorkFlowType" }, { "data": "WorkflowInstanceId" } ...

Encountering a 500 server error while attempting to retrieve content from Google Images through the Web Speech API

My current project involves utilizing the Web Speech API to dynamically gather free images from Google. Here's how it works: I extract the search keyword using the Web Speech API in JavaScript. The keyword is then sent to the server (PHP) via an a ...

Tips for incorporating the .click function with an overlay

Having some trouble using the .click function in conjunction with jQuery Tools overlay. HTML: <p id="click">Click here:</p> <div class="pop"> <div> <p>Insert text here</p> </div> </div> jQuery func ...

AngularJs $scope functions similarly to a local variable

Having an issue that needs addressing. app.controller('groupConfigCntrl', ['$http', '$scope', '$routeParams', function($http, $scope, $routeParams){ var id = $routeParams.id, info = {}; ...

Any tips for avoiding a new line when generating html attribute values to prevent my json string from breaking?

When working with JSON string values in button element attributes, I have encountered an issue where a single quote causes the value to break and create newlines. For example: var $json = JSON.stringify('{"Long_text":"This is \'my json stri ...

Encountered JSON Parsing Issue (lack of knowledge in JSON handling)

As I am moving a system from one server to another, I encountered an error when trying to access a particular page. Strangely, the code is identical to the live version of the system where it works perfectly fine. The JavaScript code causing the error is ...

Create a Container for Your Designs

I am faced with the challenge of developing a portal container using HTML5 and Javascript. This container will receive a variable number of widget URLs and it is responsible for loading them via Ajax in separate DIVs (not iFrames). My question is how can ...

Add a new key-value pair to the mock data by clicking on it

Hey there! I'm currently tackling a task that involves toggling the value of a boolean and then appending a new key-value pair on click. I've been attempting to use the . operator to add the new key-value pair, but it keeps throwing an error. In ...

Tips for implementing a handler on a DOM element

$(document).ready(function(){ var ColorBars = document.getElementsByClassName("color-bar"); var number = 0; ColorBars[0].onclick = hideLine(0); function hideLine(index){ var charts = $("#line-container").highcharts(); v ...

How can we effectively transfer a value from TypeScript/Angular?

I am new to TypeScript and Angular, and I'm struggling with assigning a value to a variable within a function and then using that value outside of the function. In regular JavaScript, I would declare the variable first, define its value in the functio ...

Utilizing regex in jQuery/JavaScript for replacing specific text areas

Can you provide a solution for isolating the currency from the text using jQuery in the following example? We need to remove all other data except the currency. We attempted using JavaScript's replace method as shown below: var symbol = $("div.pri ...

Introducing PRISMA's innovative WHERE clause that filters arrays of enums

Here is my Prisma schema: model User { id String @id @default(uuid()) email String @unique mailing_address String password String verification_token String? ...

Challenges of relative positioning with dynamic height based on content

Hello! I'm trying to achieve this https://i.stack.imgur.com/Q6lXP.png In this case, there are 3 divs. The top one will have a width of 100% and a height of auto, with relative positioning. The second div is similar, but I plan to add some dummy text ...

Achieving perfect alignment through the horizontal centering of three flexbox items with identical widths

Struggling to center these 3 items horizontally using flexbox, all of the same width. HTML: <div id="contact_flex_container"> <div id="fb"> <img src="img/contact/fb.png" class="contact_img"> <h3>Title1</h3&g ...

Updating the value of each preceding sibling of every checked checkbox using jQuery upon form submission

After extensive research, I discovered that the most effective approach involves using a clever workaround to capture every tick and untick on a dynamic input row with multiple checkbox arrays. However, none of the solutions provided a viable method. I th ...

How can you insert a value inside another in AngularJS?

My value is structured like this: app.value('opportunityStages', [ 'NEGOTIATION', 'PROPOSAL', 'PERCEPTION_ANALYSIS' ]); Although this setup works, I attempted to inject this value into another one with the fo ...

Utilizing JavaScript Files Instead of NPM as a Library for Open Layers: A Step-by-Step Guide

I've been attempting to get Open Layers to function in my Eclipse web development environment, but I've encountered some challenges along the way. The setup instructions provided on the Open Layers website focus mainly on using npm. Nevertheless, ...

Ajax requests can form a pyramid of doom when multiple asynchronous calls are structured

My JavaScript application requires making an ajax call and potentially more calls based on the previous response. Currently, I have implemented this using a somewhat cumbersome pyramid of doom: function startParentArray(id) { getIssueDetail(id).succes ...