Tips on changing the included content of a personalized directive?

Currently utilizing angular 1.x and I've crafted a personalized directive named slider as displayed in the code below.

I am attempting to integrate the content of the slider directive using transclude so that I can modify it within the transclude function. However, the issue arises when the clone does not present a collection of .slide elements. Instead, it displays a comment related to ng-repeat. It is proving difficult to retrieve the compiled output of ng-repeat, which ideally should consist of a collection of .slide divs. I would like to understand how to access the result of ng-repeat within the transclude function in order to effectively call scope.showCurrent. Currently, the $('.slide') call inside scope.showCurrent() fails to locate any .slide divs because they are not yet present during the call. If ng-repeat could provide its compiled html within the transclude function, then $('.slide') would be able to capture the divs.

app.directive('slider', function ($compile) {
     return {
          restrict: 'EA',
          priority: 1200,
          scope: true,
          controller: function ($scope) {
               $scope.slider = { currentIndex: 0 };
          },
          transclude:'element',
          link: function (scope, el, attrs, ctrl, transclude) {

               scope.showCurrent = function (currentIndex) {
                    console.log('x')
                    $('.slide').hide();
                    $('.slide').eq(currentIndex).show();
               }

               scope.$watch('slider.currentIndex', function (val) {
                    console.log('tst');
                    scope.showCurrent(val);
               });

               transclude(scope, function (clone) {
                    el.after(clone);
                    scope.showCurrent(scope.slider.currentIndex);
               })
          },
     }
});

The following snippet showcases how to use this directive in HTML.

<slider>
  <div ng-repeat="slide in slides" class="slide">
     <div>Image {{img}}</div>
     <img ng-src="img"/>
   </div>
</slider>

Take a look at my plunk https://plnkr.co/edit/m7YJBNuDjeLPaKkUYK5S?p=preview

Answer №1

When your code is running inside the transclude function, you won't get the .slide divs yet.

el.after(clone);
scope.showCurrent(scope.slider.currentIndex);

This is because the linking functions of the inner content, specifically the linking function of ng-repeat, have not been executed at that point. The watcher for the slides is added within this linking function.

Even if you wait until the linking functions have run, like in this scenario:

transclude(scope, function (clone) {
    el.after(clone);
    scope.showCurrent(scope.slider.currentIndex);
})
// at this point, the linking functions of the `clone` have already been executed

The .slide divs still won't be available until the first digest loop runs.

After making your update:

You can actually remove this part from your code:

transclude(scope, function (clone) { 
    el.after(clone); 
    scope.showCurrent(scope.slider.currentIndex); 
})

Instead, let ng-transclude handle compiling and linking the content with the correct clone. You should wait for the digest loops to run and for ng-repeat to render the div .slider elements. To achieve this, use $timeout:

$timeout(function() {
    scope.showCurrent(scope.slider.currentIndex);
}); 

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

Cross-Origin Resource Sharing is enabled yet I am still encountering the error message: "The origin has been blocked by CORS policy because no 'Access-Control-Allow-Origin' header is present."

I am facing a CORS error whenever I try to redirect the browser from the backend. Despite using the CORS package in the backend, it seems like it is not functioning as expected. Below is the code snippet from the client-side: useEffect(() => { async ...

JavaScript isn't cooperating with a straightforward .click() command

Having some trouble clicking a div using JavaScript in my project. I am able to utilize jQuery, and have tried selecting the element with QuerySelector as well as XPath, followed by utilizing .click() on the element. However, it seems that the div is not b ...

Uploading Files with Additional Information in Angular

I am currently utilizing the Angular-file-upload library to upload files to an API. This is how I'm approaching it: var uploadFile = function (file) { return $upload.upload({ url: '/api/place/logo', data: {place_id: 1, t ...

Adapting npm scripts with Node.js based on the current context

Can you set up package.json to execute a different npm start script depending on the context? For instance, I want to run DEBUG=http nodemon app.js during development. However, I prefer to run node app.js in production. ...

Is there a way to customize the outlined color of an input adornment in MUI?

Looking to customize the default blue color in a Form Control outlined variant, but can't figure out how. I was able to do it with a regular TextField, but this one is a bit trickier. <FormControl variant="outlined"> < ...

Every time I run `npm install`, I consistently encounter the `code ECONNREFUSED` error message for every

`npm ERR! code ECONNREFUSED npm ERR! errno ECONNREFUSED npm ERR! FetchError: request to http://registry.npmjs.org/body-parser failed, reason: connect ECONNREFUSED 127.0.0.1:3000` I attempted various solutions such as adjusting proxy settings and running ...

Is there a way to attach a React component to an HTML element called i?

I've been implementing the winbox modal library and have encountered an issue when trying to add a React node to it. The modal offers an html parameter that accepts an HTML string like div.innerHTML = <div>hello</div>. The code snippet is ...

Designing motion graphics for a browser game

As I delve into learning about Node.js, Angular.js, Socket.io, and Express.js, my current project involves creating a multiplayer poker game like Texas Hold 'Em. However, despite spending a considerable amount of time browsing the internet, I have bee ...

Node.js retrieves a single row from a JSON array with two dimensions

I am working with a two-dimensional JSON array and I am able to retrieve data from the first dimension using data["dimension-1"], but I am struggling to access data from the second dimension using data["dimension-1"]["dimension-2"]. What is the correct m ...

make changes to the current selection in the drop-down menu

Imagine I have a select list with 3 options: <select> <option>1</option> <option>2</option> <option>3</option> </select> My goal is to create a textfield and button that will allow me to upd ...

Unexpected syntax error encountered when shutting down the route, unable to recover

const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.get('/split/name', (req, res) => ...

grab the content from a text editor and insert it into a div element

Currently, I am trying to extract text from my content editable div and place it in another div (similar to the one seen on stack overflow). However, I am encountering a frustrating issue. 1. My content div seems to be lagging behind. When I type in my ed ...

Using the googleapis library within HTML is not permitted

I have been attempting to execute a simple function (uploadFile(test.txt)) within an HTML file, but I am encountering issues as my app.js and Google APIs are not being recognized or called. Node.js is throwing this error: Uncaught ReferenceError: uploadFi ...

Problem with Jquery Colorbox in firefox

I am using JavaScript to dynamically populate anchor links in a repeater and displaying them in a colorbox iframe. This functionality is working well in IE7, Safari, and Chrome, but encountering an issue in Firefox (version 14.1). In Firefox, the links ar ...

Best practice for entering events in callback

Recently, I delved into Angular because I anticipate needing to use it down the line. My current focus is on studying components communication, particularly from child to parent. I came across various methods of achieving this. In each example, the ChildC ...

Understanding the values of attributes when submitting a reactive form

My form is built using Angular's reactive forms and includes an input element with custom attributes: <input type="text" [attr.data-challengeId]="value.id" [formControlName]="value.label"> When I submit the form, I only receive the value of th ...

Switching things up with Angular-ui: New controller syntax for tab navigation

I'm currently working on integrating angular-ui bootstrap tabs into a basic application and running into issues with conflicting controller definitions or scope versions. var app = angular.module('plunker', ['ui.bootstrap']); // ...

The socket context provider seems to be malfunctioning within the component

One day, I decided to create a new context file called socket.tsx: import React, { createContext } from "react"; import { io, Socket } from "socket.io-client"; const socket = io("http://localhost:3000", { reconnectionDela ...

Why is the response undefined when I resize an image twice using a JavaScript promise chain?

When I attempt to resize an image using the sharp library twice in my route handler, the result returned is undefined. Despite the resized images being displayed, it seems that calling image.resize and .toBuffer() multiple times is causing corruption in th ...

Is there a way to dynamically assign ng-include or ng-controller in Angular JS?

I'm a beginner with Angular JS and after some research, it seems like what I want to achieve might not be possible. However, I'd like to explore if there is an alternative solution that can provide a similar outcome. My goal is to populate a pag ...