How to trigger a re-rendering or compilation of a ng-repeated div within an AngularJS directive

I am working with a div that utilizes ng-repeat to display items.

Initially, I have a few items in an array.

My goal is to ensure that the first item renders before the subsequent items. This is necessary due to the dependency on the height of each div.

Is there a method to achieve this?

<div class='listOne'>
    <div ng-repeat='item in listOne'>{{item}}</div>
</div>
<div class='listTwo'>
    <div ng-repeat='item in listTwo'>{{item}}</div>
</div>

JS

var myList = ['something', 'stuff', 'someOtherthing'];
var listOne = [];
var listTwo = [];

// determine where to insert the item based on height
function decideListBasedOnHeight() { // returns array
    var listOneElement = // reference to listOne element
    var listTwoElement = // reference to listTwo element
    if (listOneElement.offsetHeight > listTwoElement.offsetHeight ) 
       return listTwo;
    return listOne;
}

forEach (myList, function(value) {
    decideBasedOnHeight().push(value);
});

Example illustrating the issue: http://plnkr.co/edit/XxJTzNlnQrB7S7tQ0PBL?p=preview Another example: http://plnkr.co/edit/3pzpsgmQ0vIM1e6nuEQG?p=preview

Answer №1

What an intriguing question!

Instead of using forEach on an array, consider pushing the elements one by one through a directive. Take a look below:

<div ng-contoller="ctrl">
    <div class='listOne'>
        <div ng-repeat='item in listOne' count-height-and-push-next="listOneHeight">{{item}}</div>
    </div>
    <div class='listTwo'>
        <div ng-repeat='item in listTwo' count-height-and-push-next="listTwoHeight">{{item}}</div>
    </div>
</div>

.directive('countHeightAndPushNext', function(){
   return{
       restrict: 'A',
       scope: true,
       link: function(scope, element, attrs){
           scope[attrs.countHeightAndPushNext] += element[0].outerHeigth;
           scope.pushItem();
       }
   };

})

.controller('ctrl', function($scope){
    $scope.myList = ['something', 'stuff', 'someOtherthing'];
    $scope.listOne = [];
    $scope.listOneHeight = 0;
    $scope.listTwo = [];
    $scope.listTwoHeight = 0;

    var nextPushIndex = 0;
    $scope.pushItem = function(){
        if($scope.listOneHeight > $scope.listTwoHeight){
             $scope.listTwo.push($scope.myList[nextPushIndex])
        }else{
             $scope.listOne.push($scope.myList[nextPushIndex]);
        }
        nextPushIndex++;
    };
    $scope.pushItem();
});

I find the tight coupling in this example to be less than ideal and believe it requires some refactoring and fine-tuning. Nonetheless, this approach should do the trick for now. Cheers!

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

Experiencing a service error when trying to load in certain browsers, although it does work properly in Chrome and

I am facing an issue with my service method which is showing errors in multiple browsers including Internet Explorer 8, Chrome, and Firefox 8.0.1. The error message is: OPTIONS http://abc/AddRating 405 (Method Not Allowed) Interestingly, the service met ...

Utilizing Material-UI List components within a Card component triggers all onClick events when the main expand function is activated

Need help with Material-UI, Meteor, and React I am trying to nest a drop down list with onTouchTap (or onClick) functions inside of a card component. While everything renders fine initially, I face an issue where all the onTouchTap events in the list tri ...

Using TypeScript to retrieve a strongly typed promiseValue from an angular $modalInstanceA

New to TypeScript Question: I'm working on returning a strongly typed promise from angular's $modalInstance. Here is an example of what I have: this.$modal.open(options).result.then(result => { At the moment, 'result' is of typ ...

Perform an ajax POST call to a server using ajax/jQuery techniques

I am attempting to utilize ajax to send a post request to a different domain and receive a json response. The server is located within my company premises and the logs show that it is indeed sending back a json response. Below are two samples of my attemp ...

Placing files in the "Dist" folder is causing an issue by disrupting the functionality of the Angular 2 app

For testing my login component in Angular2, I am using a mockBackend within my app. Initially, the standalone version of the login worked perfectly fine. However, when trying to integrate it into my ongoing development project, I encountered an issue. Duri ...

Issues with the functionality of the shopping cart are causing a disruption

This is the coding for the online shopping cart: <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8" /> <title>Online Shopping Cart</title> <script src="jquery-3.1.1.min.js"></script> ...

Guidelines for showcasing validation summary on an ASP.NET webpage with the help of Javascript

My asp.net form contains multiple required fields that need validation. I am looking to display a summary of all validations at the end of the form. Valid input controls have already been checked, now I just need the summary. Here is an example code s ...

Error: Cannot access the 'question' property of an undefined node

I am facing an issue with a command-line application that I am currently transitioning into a client/server application. Within the class I have written, there is a function responsible for randomly extracting questions. However, I have observed instances ...

Error Found in Angular2 Console Inspection

So, when I check the webpage inspection console, I see this error: Uncaught SyntaxError: Unexpected token { at Object.<anonymous> (main.bundle.js:3885) at __webpack_require__ (polyfills.bundle.js:51) at eval (eval at <anonymous> (m ...

Navigating from an error page to the homepage with Next.JS 13: A quick and easy guide

I'm currently working on implementing a feature that allows users to easily go back to the main page from an error page within the app folder. Specifically, in my weather app project, if a user enters an incorrect city, they should have the option to ...

Guide to authenticating Chinese email addresses within an AngularJS framework

My project involves validating English and Chinese language using AngularJS and PHP. <form name="form" class="form-validation"> <div class="mail"> <input type="email" name="email" ng-model="email" placeholder="Email 邮箱" requ ...

Switch up the text within the URL of the background image

Simply put, this is the structure I have: <div id="RelatedPosts1"> <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-1.jpg)"></div> <div class="related-posts-thumb" style="background: url(http: ...

What is the meaning of MVVM "binder" and how is it used?

I've been conducting research online to gain a deeper understanding of the MVVM architecture in general. According to Wikipedia, the key components of the MVVM pattern are: Model View View Model Binder This is the first time I have come across the ...

What are the steps to configure ESlint and Prettier with the Airbnb style guide for a React Native/JavaScript project (Expo) in VS Code?

I have looked through numerous tutorials on this topic, but I haven't been able to get it to work. In the tutorials, when you run npm install eslint, it usually prompts you in the command line about using a popular style guide. However, this no longer ...

JavaScript is failing to execute the DELETE SQL transaction

I've been attempting to clear out my html5 local sql database, but for some reason, it's not working as expected. Below is the code I'm using, and no matter what I try, the alert always shows that the length is greater than 0. Any ideas why ...

What is the process for triggering a sorted output from my MongoDB database by simply clicking a button?

I'm struggling with sorting my collection by rating in my code. I have this snippet where I'm sending my collection to index.ejs: router.get('/', (req, res) =>{ FILM .find().limit(6) .then(films => res.render(& ...

Clearly defined form field even with the inclusion of value=" "

I have a database that I am using to display data in an HTML form for user editing. <input type="text" id="name" placeholder="Name" required = "true" value = <?php if(isset($_SESSION['name'])) echo $_SESSION['name'] ;?>> ...

Node.js Passport Authentication: Simplifying User Verification

I need assistance with the following code as I am encountering errors during execution. Can someone help me in setting up routes for both login and register forms that are located on the same page? When trying to submit the registration form using this cod ...

What is the recommended data type to assign to the `CardElement` when using the `@stripe/react-stripe-js` package in TypeScript?

I'm struggling to determine the correct type to use for this import: import { CardElement } from '@stripe/react-stripe-js'; I have successfully used the types Stripe, StripeElements, and CreateTokenCardData for the stripe and elements props ...

How to personalize your Fullcalendar event tooltips with custom profile images

I recently integrated the Fullcalendar plugin by Adam Shaw with Bootstrap 3 on my website to display events created by users. Each event has a popover script that provides additional information when clicked. One feature I would like to add is displaying ...