Make sure to execute the fire directive only when ng-repeat has completed

Currently, I am utilizing owl carousel with data being fetched through an Ajax call. Once the data populates the HTML content using ng-repeat, I need to trigger the directive that initializes the owl carousel. How can I achieve this?

One approach I considered was using the onFinishedRender directive, but unfortunately, it did not work as expected.

Directive:

directives.directive('onFinishRender',['$timeout', '$parse', function ($timeout, $parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                    if(!!attr.onFinishRender){
                      $parse(attr.onFinishRender);
                    }
                });
            }
        }
    }
}]);

Controller:-

pastWorkService.getAllPastWork()
    .success(function(data) {

        var len = data.length;
        $scope.pastWorkData1 = data.slice(0, len/2);
        $scope.pastWorkData2 = data.slice(len/2, len - 1);
        $scope.owlCarouselPastWork1 = function(){
            $('.owl-carousel2').owlCarousel({
                items: 4,
                loop:true,
                slideSpeed : 1000,
                autoPlay: 3000,
                itemsDesktop: [1199, 4],
                itemsDesktopSmall: [980, 3],
                itemsTablet: [768, 3],
                itemsTabletSmall: false,
                itemsMobile: [479, 1],
                navigation: false
            });
        };
        $scope.owlCarouselPastWork = function(){
            $('.owl-carousel1').owlCarousel({
                items: 4,
                loop:true,
                slideSpeed : 1000,
                autoPlay: 3000,
                itemsDesktop: [1199, 4],
                itemsDesktopSmall: [980, 3],
                itemsTablet: [768, 3],
                itemsTabletSmall: false,
                itemsMobile: [479, 1],
                navigation: false
            });
        };
    });

HTML:-

<div class="owl-carousel1" role="listbox" >
    <div class="item" ng-repeat="p in pastWorkData1" on-finish-render="owlCarouselPastWork1()">
        <img src="{{p.mainImage}}" alt="completed-projects" />
        <div class="panel-footer">{{p.apartmentName}}</div>
    </div>
</div>
<!-- The second row will follow suit within the owl carousel -->
<div class="owl-carousel2" role="listbox" >
    <div class="item" ng-repeat="p in pastWorkData2" on-finish-render="owlCarouselPastWork1()">
        <img src="{{p.mainImage}}" alt="completed-projects" />
        <div class="panel-footer">{{p.apartmentName}}</div>
    </div>
</div> 

Answer №1

If your goal is to execute a function after the last repeated item has been rendered, here is a suggested approach:

HTML

<div class="owl-carousel1" role="listbox" >
    <div class="item" ng-repeat="p in pastWorkData1">
        <img src="{{p.mainImage}}" alt="completed-projects" />
        <div class="panel-footer">{{p.apartmentName}}</div>
        <span ng-if="$last" on-finish-render function-to-call="owlCarouselPastWork()"></span>
    </div>
</div>
<!-- Second row goes here as owl carousel can contain 1 row -->
<div class="owl-carousel2" role="listbox" >
    <div class="item" ng-repeat="p in pastWorkData2">
        <img src="{{p.mainImage}}" alt="completed-projects" />
        <div class="panel-footer">{{p.apartmentName}}</div>
        <span ng-if="$last" on-finish-render function-to-call="owlCarouselPastWork1()"></span>
    </div>
</div> 

Directive

.directive('onFinishRender', function($timeout) {
    return {
        restrict: 'A',
        scope: {
            functionToCall: '&'
        },
        link: function(scope, elem, attrs) {
            $timeout(function() {
                scope.functionToCall();
            });
        }
    }
})

Here's a simple example to demonstrate this concept. It may be possible to refactor this code by moving the function into the directive and passing the desired class identifier to call it on.

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

Checking the list box and radio button using JavaScript based on their respective IDs

Looking to validate the selection of a listbox and radio button using their respective IDs when a submit action occurs. When testing in the browser, no alert is being displayed. The goal is to trigger the script upon clicking the submit button to verify ...

Strategies for Restricting Dependency Injections in AngularJS

In implementing dependency injections within my controllers, I utilized the following syntax. .controller('deals_list', function ($scope, global, config, services, dealService, pagination) { As the application continued to expand, the number o ...

Firefox does not allow contenteditable elements to be edited if they are nested inside a parent element that is draggable

Here is a basic HTML example: <div draggable=true> <div contenteditable=true>can't edit me</div> </div> When testing in Chrome, I noticed that I was able to edit the contents of the contenteditable div, however, this functi ...

Angular has developed a content script that automatically fills in user passwords on forms

I have developed a content script extension that automatically fills in user and password fields on webpages. It works perfectly fine on regular forms like the one below - <input name="userId" class="form-field" id="userId" placeholder="Username" autoc ...

Why is the Slick Slider displaying previous and next buttons instead of icons?

I'm currently working on creating a slider using the slick slider. Everything seems to be functioning properly, but instead of displaying arrows on the sides, it's showing Previous and Next buttons stacked vertically on the left side. It appears ...

6 scenarios where Angular JS would be beneficial

Even though I have experience working with knockout JS and Angular JS, I still find myself uncertain about when it is best to implement Angular JS in real-world project scenarios. Currently, I am incorporating Angular with MVC, but I am unsure if I should ...

jQuery - Issue with triggering events after using the .load() method

This is the code snippet I am working with: function refresh () { sub_tab=$("#hid").val(); $("#content").load(cur_tab+'.php',function () { alert(sub_tab); $("#pd").trigger('click'); }); } The line $ ...

Rails may encounter issues with the format of parameters in ajax requests at times

Something strange is happening with my form: The form looks like this: <form id="my-form" method="post" action="/password_reset/update/<%= @user.perishable_token %>" charset="utf-8" autocomplete="off"> <input type="password" name="use ...

Attempting to insert the symbol "$gt" into a query for a search. {[CastError: Unable to convert value "[object Object]" to date at path "createdAt"]}

In the following code snippet: Reviews.find({createdAt : {"$lt" : app.locals.lastDate}}), I am trying to dynamically change the $lt to $gt. app.post("/scroll", function(req, res){ console.log("req.body...", req.body); var sortCreate = req.body.old ...

Instructions on activating dark mode with the darkreader plugin on a Vue.js website

Is there a way to implement DarkMode in a Vue.js application? I attempted to integrate darkmode using this npm package, but I kept encountering the error message: DarkMode not defined. ...

Sort products by the subcategory in Firebase

I am currently facing a challenge in filtering products based on their sub child nodes within Firebase. This is how my data is structured: products/ product1 /author: 12345 /title: "Awesome" /description: "more awesome" ...

What is preventing me from making an inline call to res.json?

In my expressjs application, I encountered an issue with inlining a callback when using the res.json method to respond with a database document. While inlined calls to console.log worked fine, the program failed when I attempted the same approach with res. ...

Can buttons be inserted into an Input control?

I am currently working on developing a custom timepicker that is compatible with both Internet Explorer and Chrome. The desired time format is 'hh:mm'. This is what I have so far: <input ng-model="timeHours" type="number" class="hours" placeh ...

My code fails to recognize the top property when the window size is 1300px

Error at the Top Not Being Recognized: Hello, I am facing an issue where the top part of the webpage does not behave correctly when the window size is less than 1300px. The condition set for 100% top only applies after refreshing the page; otherwise, it d ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

The styling of MUI components adapts when the Navigate component in React Router is initialized

Incorporating React Router into my application has led to an unexpected side-effect while implementing the <Navigate to="/"> component (which goes to <AthleteHomepage />) upon state change. Currently, I haven't set up dynamic sta ...

Images in the JavaScript menu are not remaining fixed in place

Can someone help me with my website? I'm having trouble with the menu for different pages, it should stay gray for the active page. It was working fine before I switched to Wordpress, but now I'm not sure what the issue is. Could someone take a ...

Display toolbar title on small screens in separate lines

Recently, I encountered an issue while using v-toolbar in my vue app. Despite my efforts, I couldn't find a way to split the title into multiple lines on small screens. Currently, it displays as "Secti...." on smaller devices. Can anyone assist me wit ...

Formatting AngularJS ng-repeat into individual cells

Struggling to achieve a layout like this using ng-repeat with a <table>. instrument1 instrument4 instrument7 instrument10 instrument2 instrument5 instrument8 instrument11 instrument3 instrument6 instrument9 instrument12 Presenting my code.. &l ...

"Change opacity smoothly with the FadeToggle feature for a

I have a question that might seem silly, but I can't quite figure it out. How can I extend the duration of the fade effect? window.switchIn = function() { $('.red').fadeToggle(function(){ $('.blue').fadeToggle(function() { ...