Angular directive that repeats nested directives should only pass if the parent directive is the last one

I need to trigger an event once all the iterations in this nested loop are completed. While I can use $last to check for the last iteration, I am unable to determine within the inner loop if it is at the $last iteration of the parent loop. Here's what I have:

<div>
    <div ng-repeat="filter in filters.filters" repeat-directive-one filter="filter" update-filter="updateFilter">
</div>
</div>

Inside the repeat-directive-one looks like this:

<div ng-repeat="item in filter.values | limitTo: filter.showMore ? filter.values.length : '5' track by $index" repeat-directive-two value="::item" update-filter="updateFilter" ng-if="!$last"></div>

<div ng-repeat="item in filter.values | limitTo: filter.showMore ? filter.values.length : '5' track by $index" repeat-directive-two value="::item" update-filter="updateFilter" ng-if="$last" checkbox-fix></div>

This setup adds the checkbox-fix directive when it reaches the last item of the inner loop. However, this fires multiple times if the outer loop has fewer items than the inner one. I would like something like:

ng-if="$last && parent.$last"

But this logic doesn't seem to work as expected. I also tried passing the parent $last boolean as a isolated scope attribute (in repeat directive one):

<div ng-repeat="filter in filters.filters" repeat-directive-one filter="filter" update-filter="updateFilter" last-property="$last">

However, logging $scope.lastProperty returns nothing. Is there a way to pass down a flag indicating that the parent loop is at its $last iteration? Any suggestions would be appreciated. Thank you!

Answer №1

In order to signal when the outer loop is finished and trigger the final iteration of the inner loop, you can implement something similar to this:

<div ng-repeat="stuff in stuffs" outer-loop>
    <div ng-repeat="item in items" inner-loop></div>
</div>


angular.module('test').directive('outerLoop', function($rootScope){
    return function(scope, element, attrs) {
        if (scope.$last){
            $rootScope.$broadcast('outerLoopComplete');
        }   
    };
});

angular.module('test').directive('innerLoop', function(){
    return function(scope, element, attrs) {
        var outerLoopComplete = false;

        scope.$on('outerLoopComplete', function(){
            outerLoopComplete = true;
        });

        if(outerLoopComplete && $last){
            //inner loop complete
        }
    };
});

Answer №2

With guidance from @trevor, I managed to solve the issue in the following way:

<div ng-repeat="item in filter.values | limitTo: filter.showMore ? filter.values.length : '5' track by $index" repeat-directive-two value="::item" update-filter="updateFilter" checkbox-fix></div>

I attached the checkbox-fix to the repeat directive (eliminating the need for 2 toggles using ng-if), and within the checkbox-fix directive, I implemented the following:

 return {
        restrict: 'A',
        link: function(elem, attr, tr) {
           if(elem.$parent.$parent.$last && elem.$last){
                //issue resolved!
           }
        }
    };

The use of elem.$last was successful, although I had to examine the data/structure more closely to understand that I needed to use elem.$parent.$parent.$last instead of just one level of parent.

Answer №3

Learn more about ngInit directive here

Utilize ngInit to assign the value of $last to a scope variable, enabling direct and indirect access to this variable from the child scope, particularly in cases involving isolate scope.

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

Leveraging both onmouseover and onmouseout for container expansion

My goal is to utilize JavaScript along with the HTML events "onmouseover" and "onmouseout" to create a dynamic container. Essentially, I want the container to act as simply a heading when the mouse is not hovering over it, but expand to display additional ...

Running a JS/JSON function in Snowflake that results in a syntax error

Can anyone help me troubleshoot the issue with the following function? I am receiving this error message: SQL compilation error: syntax error line 1 at position 0 unexpected 'function'. Should I be using JSON Script or Javascript for this? func ...

Activate real-time highlighting by clicking on the search button

I created a simple program that searches for a value within a div and displays the first location of the word. However, I am looking to enhance it by highlighting all repeated locations of the searched word after pressing the search button. <html> & ...

Sending Email Form in PHP using JQuery and Ajax for seamless user experience

Looking to create an email form in HTML with PHP, but running into the issue of the page reloading after submitting? Many people turn to jQuery and AJAX to solve this problem. While you may have come across solutions on Stack Overflow, as a non-native Engl ...

Separating unique values in an array of objects and storing the rest of the values in a separate

I have an array of JavaScript objects that I need to merge into a single JavaScript object based on their same property value. The remaining values should be grouped into another array named info. Original array: const array = [ { price: 27, ...

AngularJS secureHTML verify image click event

Just starting out with AngularJS and hoping for some assistance :) I have a div that has the details of an activity, formatted in HTML. To display this content correctly, I am using trustAsHTML: <div class="description-div"> <div ng-bind-htm ...

Having trouble with npm install, unable to successfully install any node modules after cloning my project from git

I recently pulled my project from a git repository and encountered issues while attempting to run npm install. Despite trying different solutions like running npm install --save core-js@^3 to address the core-js error, I keep receiving the same message pr ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

Using Node.js to send a photo through a Telegram Bot

I've been trying to send a photo via node.js using this function, but it's not working. telegram-bot-api https://www.npmjs.com/package/telegram-bot-api var telegram = require('telegram-bot-api'); var api = new telegram({ token: & ...

Using AngularJS to dynamically update the DOM with the response from a service method

Here's the HTML code: <div ng-controller="AutoDeployController as autoDeploy"> <input type="text" ng-model="autoDeploy.message"> <p>Message: {{ autoDeploy.message }}</p> </div> <button ng-click="autoDeploy.chan ...

Is there a way for me to retrieve a variable from within a .then function nested within another .then function?

Here is an example of code where I am attempting to log the value of 'a' to the console. driver.sleep(2000).then(function logAInConsole() { var a = ["Quas","Wex","Exort","Invoke"]; for(var i = 0; i < a.length; i++) { driver.sleep( ...

An unexpected glitch causes Parse server to crash

Currently, I am experimenting with using kue for scheduling jobs on my Parse Server which is hosted on Heroku. Following the guidelines from various tutorials I found regarding Kue, I made some modifications to my index.js file as shown below: var express ...

Nesting ng-repeat within another ng-repeat for dynamic content generation

I am currently working on a page that requires displaying boxes (using ng-repeat) containing information about channels and their corresponding cities. The issue I am encountering arises when repeating the second ng-repeat: <table class="table table-c ...

Multiplication cannot be performed on operands of type 'NoneType'

Hello everyone, I am attempting to calculate the unit price and quantity from this table using the following model: class Marketers(models.Model): category =models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name =models.CharField(max ...

Convert a pandas dataframe into a JSON object with nested structures

Someone raised a similar question in a different forum, which was expertly answered by user1609452 using R. However, I believe there is more to explore with this topic. Let's consider a table (MyData) that looks like this: ID Location L_size L_co ...

Google Maps API - Custom Label for Map Markers

I am trying to implement a custom map on my website, and everything seems to be working fine except for one issue. The red marker on the map needs to have a label, but I don't want to use an additional image as an icon. Is there a way to add a label ...

The module './installers/setupEvents' could not be located within Electron-Winstaller

After encountering an error while attempting to package my Angular app on Windows 10, I'm looking for help in resolving the issue: https://i.stack.imgur.com/yByZf.jpg The command I am using is: "package-win": "electron-packager . qlocktwo-app --ove ...

Obtaining a value from within an Angular 'then' block

I have a unique issue that I haven't been able to find a solution for on StackOverflow: Within an Angular 6 service, I am trying to call a function from another service using TypeScript. Here is the code snippet: Service1: myArray: Array<IMyInte ...

How can we determine if a Node.js application will remain operational?

How is the longevity of a Node.js app determined? For example, consider this code snippet: console.log('Hello World'); In this case, the phrase will be printed and the app will exit immediately. However, with a web server that is actively lis ...

What's the reason behind this file not opening?

When I try to insert this code into files index.html, style.css, and app.js, the page refuses to open. The browser constantly displays a message saying "The webpage was reloaded because a problem occurred." I am using a MacBook Air with macOS Big Sur and a ...