Implement a method within a directive

Check out my custom Angular directive code below, which generates div elements:

function footerDirective($compile){
     return { 
         link: function(scope,elements,attributes){

             function createDiv(content,cname,callback){
                var new_div=document.createElement("div"); 
                new_div.setAttribute("ng-click", callback);
                $compile(new_div)(scope);
                new_div.innerHTML=content;
                new_div.className=cname;
                elements[0].appendChild(new_div); 
             }

     for (var i=0;i<5;i++) {
       createDiv(i,"class-numbers","gallery.clickPage()");
     }
}}}

In the code snippet above, gallery.clickPage refers to a Controller method. It functions properly as is. However, I am trying to pass i as an argument into gallery.clickPage, like so:

gallery.clickPage.bind(this,i)

Unfortunately, when I attempt to pass this into the createDiv function, it does not work. How can I make this modification successfully?

Answer №1

The correct approach is to include the following in the template:

<div ng-repeat="mydiv in mydivs" ng-click="gallery.clickPage($index)">{{mydiv.content}}</div>

And in the directive:

scope.mydivs = [{content : 1}, {content : 2}, ...]

To address your question: the i you mentioned is phantom - it doesn't exist when the page is viewed, only during its creation by Angular. Therefore, you can't pass it directly. Instead, you can do something like this:

createDiv(i,"class-numbers","gallery.clickPage(" + i + ")")
;

Alternatively, you could assign the values of i to the scope: scope.myVars = [1, 2, 3, 4, 5]

createDiv(i,"class-numbers","gallery.clickPage(myVars[" + i + "])")
;

A final important point to note is that if you wish to create an Angular element, you can simply do so like this:

angular.element('<div ng-click="someF()">{{anything}}</div>')
, then compile and append it to the parent element.

Answer №2

Consider utilizing the following approach:

 for (let i=0; i<5; i++) {
   createDiv(i, "class-numbers", "gallery.clickPage(" + i + ")");
 }

If 'i' is only a number, it can be passed as shown above, resulting in HTML like gallery.clickPage(1), and so on.

This will effectively pass 1

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

How can you efficiently update another ng-model value based on a select input in AngularJS using ng-change?

<select data-ng-init="selectedItem='previewWidth = 1920; previewHeight = 1080'" data-ng-model="selectedItem" data-ng-change="GetNewData(); {{selectedItem}}"> <option value="previewWidth = 1920; previe ...

Is there a way to use require in react-native to pass multiple images at once?

In my React Native project, I'm trying to upload multiple images and display them on a map. However, when I attempt to pass the URLs of local images to the map component, I encounter the following error: Error: Invalid call at line 62: require(url) ...

What is the best way to specify the CSS :hover state within a jQuery selector?

I am trying to change the background color of a div element when hovered using jQuery, but for some reason the following code is not working as expected: $(".myclass:hover div").css("background-color","red"); Can someone provide guidance on how to achiev ...

How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object. The JSON object is fetched through the Relayr Javascript API, and looks like this: relayr.devices().getDeviceData({ token: tok ...

Converting timestamps: Retrieve day, date, hour, minutes, etc. without utilizing the "new Date()" function

Currently developing a web-app and faced with the challenge of displaying items in a list correctly. I am working on converting the timestamp attached to each item into a readable format. For instance, 1475842129770 is transformed into Friday, 07.09.2016 ...

Utilizing URLs as video sources in the @google/generative AI framework within a Next.js environment

Currently, I am facing an issue while trying to upload videos from a URL using @google/generative-ai in Next.js. While I have successfully learned how to work with videos stored on my local machine, I am struggling to do the same with videos from external ...

The radio button in the HTML form is disabled when the user selects

I have two radio buttons labeled Billable "Y" and Billable "N". These radio buttons are linked to a database with corresponding values of "Y" or "N". If the user selects "Y" using the radio button, then the NonBillableReason text box should be disabled. ...

Trouble with Ajax program loading properly in Chrome browser

I have developed a small ajax program and encountered an issue. While it works perfectly fine on Internet Explorer 11, it does not function correctly on Chrome and Firefox. Here is the HTML file snippet: <html> <head><title>Ajax Page< ...

NextJs does not allow external synchronous scripts

I am currently working with Next.js version 11.x Whenever I attempt to add an external script like the example below, I encounter an error when executing the yarn build. <Head> <link rel="stylesheet" type=" ...

Guide on changing query using Ajax and Laravel when clicking a link

I am currently facing a challenging issue that seems unsolvable (I'm struggling to even understand where to begin). I have a total of four hyperlinks: https://i.sstatic.net/kn5vx.png When landing on the page initially, all the links are displayed b ...

The functionality of the String prototype is operational in web browsers, but it encounters issues

Version: 8.1.0 The prototype I am working with is as follows: String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') ...

Switching left navigation in material-ui when the user interacts within the application boundary

I am currently implementing a toggle feature in my AppBar to display the LeftNav. I have successfully set it up to close when the toggle is clicked again. However, I wish to mimic the behavior of most left nav bars where clicking anywhere outside of the ...

Retrieving an ID from one controller and incorporating it into another controller's API request

Here is my original module: angular.module('ngApp', []) .factory('authInterceptor', authInterceptor) .constant('API', 'http://myserver.com/ecar/api') .controller('task', taskData) function taskData($scope ...

Locate the generated ID of the inserted child when saving the parent in MongoDB

If I have a document representing a post with comments like the one below: { "_id": "579a2a71f7b5455c28a7abcb", "title": "post 1", "link": "www.link1.com", "__v": 0, "comments": [ { "author": "Andy", "body": "Wis ...

Dynamic HTML text colors that change rapidly

I have an interesting question to ask... Would it be possible to create text that switches between two colors every second? For example, could the text flash back and forth between red and grey? I don't mean changing the background color, I mean act ...

I am experiencing difficulty transitioning the view in React Native from a side position to an inward direction

Currently tackling a design project and encountering a roadblock in achieving a specific curved effect. Here are two images for reference: The Desired Design: My Current Progress: The basic structure is in place, but hitting a wall when attempting to cu ...

Using a combination of nested fetch() and array.map() does not allow for the return

My previous coding experience didn't present any issues with rendering HTML. Typically, I only needed to use one fetch() function. However, in this particular scenario, it appears that I require two fetch calls. The first fetch retrieves a product ID ...

The installation of the Java package via npm failed with the error message: "Unable to access include file: 'jni.h'. File or directory not found."

Encountering issues with the npm install java command in Windows cmd. The 'jni.h' file is located in the INCLUDE variable within the Windows Environment Variables at C:\Program Files\Java\jdk-15.0.2\include. Include variable ...

Discovering and revising an item, delivering the complete object, in a recursive manner

After delving into recursion, I find myself at a crossroads where I struggle to return the entire object after making an update. Imagine you have an object with nested arrays containing keys specifying where you want to perform a value update... const tes ...

Solving the issue of image paths within external SCSS files in Nuxt.js

Trying to organize my component scss files separately from their Vue components has been a bit challenging. I also have a GLOBAL scss file that is not scoped, but no matter which approach I take, I can't seem to get the image paths in /assets or /stat ...