Issues arising from ng-repeat and dynamically loaded content in a directive

I have developed a directive that utilizes the jCarousel plugin to display content loaded dynamically via ajax.

Below are snippets of my code:

Using the directive in HTML:

<div class="jcarousel" dates-carousel dates="dates"></div>

where dates is an array loaded dynamically via ajax through one of my services

The Directive

datesCarouselDirective = function() {
  return {
    restrict: "A",
    scope: {
      dates: "="
    },
    templateUrl: "...",
    link: function($scope, $element, $attrs) {
      var jcarousel = $element;
      jcarousel.on("jcarousel:reload jcarousel:create", function() {
        var width;
        width = jcarousel.innerWidth() / 3;
        return jcarousel.jcarousel("items").css("width", width + "px");
      }).jcarousel({
        wrap: "null"
      });
      $element.find(".jcarousel-control-prev").jcarouselControl({
        target: "-=1"
      });
      $element.find(".jcarousel-control-next").jcarouselControl({
        target: "+=1"
      });

      console.log($scope.dates); // returns []
      console.log($scope.dates.length);  // returns 0
    }
  };
};

The Directive's Template:

<ul>
  <li>(ng-repeat="date in dates")
    {{date.format("MMM D")}}
  </li>
</ul>
<a class="jcarousel-control-prev">
  <i class="fa fa-angle-left"></i>
</a>
<a class="jcarousel-control-next">
  <i class="fa fa-angle-right"></i>
</a>

Since dates within the directive is initially set to [] (it appears that the ajax data loads after the directive has been rendered), the jCarousel functionality is not working correctly. Can someone provide assistance on resolving this issue and guide me on how to ensure proper functionality of my directive or suggest any necessary refactoring?

Answer №1

After some careful consideration, I believe I have found a resolution. Within my link function, I utilized $watchCollection to detect when the dates array is no longer empty before triggering jCarousel. It may not be the most elegant solution, but it gets the job done for me.

  link: function($scope, $element, $attrs) {
    return $scope.$watchCollection('dates', function() {
      var jcarousel;
      if ($scope.dates.length) {
        jcarousel = $element;
        jcarousel.on("jcarousel:reload jcarousel:create", function() {
          var width;
          width = jcarousel.innerWidth() / 3;
          return jcarousel.jcarousel("items").css("width", width + "px");
        }).jcarousel({
          wrap: "null"
        });
        $element.find(".jcarousel-control-prev").jcarouselControl({
          target: "-=1"
        });
        $element.find(".jcarousel-control-next").jcarouselControl({
          target: "+=1"
        });
      }
    });
  }

Is there a more efficient and suitable approach that someone could suggest?

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

What's the scoop on ng-animate and personalized directives?

How can I add custom animation to my custom directive successfully? .directive('home', function ($animate) { return { templateUrl: 'views/pantone-inner-home.html', restrict: 'AE', link: function postLink( ...

Desiring the standard back button feature of a browser to work seamlessly when loading pages via ajax requests

I am currently developing a web application in PHP and implementing the use of AJAX requests to retrieve pages from the server. For example, when a user clicks on menu tabs, an AJAX request is made to the server to fetch the page and load it into a specifi ...

Updating Button Color for Individual Button in ngRepeat Generated Button Array

I am having trouble using ngRepeat to generate four buttons. My goal is to change the color of a button and execute a function every time it is clicked (currently just using console.log). Additionally, I want the previously clicked button to revert back to ...

Tips for improving the product filtering functionality in a React application

To solve the problem, we need to develop a Filter.jsx component that will be responsible for filtering Products.jsx (available in the repository). Current React Components : Main.jsx import React from "react"; import { Products } from "../ ...

issue with vue-html2pdf when using Persian language

Is there a solution for handling Persian language issues in vue-html2pdf? Or is there another module that can convert VUE to PDF without any problems with RTL language support? ...

Exploring the magic of ng-model and ng-bind-html with AngularJs

My Markup <div ng-app="myApp" ng-controller="myCtrl"> <input type="text" ng-model="name"> <p ng-bind-html="myText|unsafe"></p> </div> This code is being utilized var app = angular.module("myApp", ['ngSanitize&a ...

The absence of variable declaration in a 'for...of' loop is functional in .js files but does not work in

index.js let items = [{ item: 'apple' }, { item: 'banana' }, { item: 'orange' }]; for (item of items) { console.log(item); } Execute using node $ node index.js { item: 'apple' } { item: 'banana' } { ...

What is the best way to send the totalAmount data from one child component to its parent, and then pass it on to another

I am facing an issue with passing the totalAmount data from cart.js to the parent component (app.js) and then further to another child component (info.js). Despite my attempts, it seems like I am unable to pass it correctly as I encounter the following err ...

Display a modal when the checkbox is ticked or unticked

For access to my code, please click on this link: http://plnkr.co/edit/Z7QI9Ec53zfkDylnseAc?p=preview Here is the HTML: <ul> <li ng-repeat="album in albums"> <input type="checkbox" ng-model="album.selected" value={{album.name}} ng-click= ...

Obtain a value using a jQuery for-in loop

I have multiple items stored in a database, each item has a unique ID assigned to it which is included in a link within the href attribute. My goal is to extract the IDs from these links that are generated within a PHP while loop. I attempted to use a for ...

What strategies can I use to ensure that I can successfully send 3,000 requests to the Google Drive API using node.js without surpassing

I'm currently assisting a friend with a unique project he has in mind. He is looking to create 3000 folders on Google Drive, each paired with a QR code linking to its URL. The plan is to populate each folder with photos taken by event attendees, who ...

Execute a zoom out action by pressing the (Ctrl) and (-) keys simultaneously in Javascript

I'm trying to figure out how to simulate a Ctrl - zoom out using Javascript. I've noticed that using the style zoom property or the transform property gives different results with white space in the corners, rather than the smooth zoom out effect ...

Retrieving form elements in Angular

I need to extract the element name and class from a form passed to a function. Is there a way to accomplish this? On the HTML side: <form name="test"> <div> <input type="text" class="test1" name="test2"/> </div> ...

Unresponsive bootstrap carousel slide controller

Could you help me with an issue I'm encountering? I have multiple HTML pages, with index.html containing a Bootstrap carousel that displays several images. I am using ngroute to connect all the HTML pages. The problem I am facing is that when I load t ...

Sticky box fails to maintain position as header scrolls

I am looking to create a Sidebar that sticks to the window while scrolling, but stops when it reaches the footer. I have managed to get it partially working, but there is a small issue that I can't seem to solve. Test it live here: Everything seems ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...

Looking for jQuery developers to notify users that IE6 is not compatible

Currently, I am in the process of creating an app and have decided not to offer support for IE6. I want to ensure that users on IE6 understand this decision and do not assume the developers lack skills. I had hoped to find a JQUERY Plug-In that could easi ...

The homepage on Delphi is having trouble displaying the menus

My issue is not related to resolving a problem with a specific IDE, such as Delphi, but rather about identifying the root cause of the issue. As many of you may be aware, in Delphi 2010 (and possibly in earlier versions), there is a welcome page that displ ...

Does AngularJS ng-if function appropriately in every module?

I've been working on showing and hiding my drag and drop feature when a document is brought onto the screen using AngularJS. It initially worked, but now I'm facing issues in certain modules even though the code remains consistent across all modu ...

What are the best tools to develop a browser-based 2D top-down soccer simulation?

I'm looking to create a 2D top-down soccer simulation game for web browsers using modern technologies and without the need for additional plugins like Flash or Silverlight, making it compatible with mobile devices as well. The game will be AI-controll ...