Send a collection of items to directives using a function

I need assistance in creating a directive that can dynamically insert buttons into a div. I have set up a json to store the button text, class, and action, but for some reason, the function does not trigger when the button is clicked. Can anyone point out my mistake?

Here is the template for the directive:

<div>
    <button ng-repeat="button in buttons" ng-class="button.class" ng-click="button.action">
        {{ text }}
    </button>
</div>

The directive code looks like this:

.directive("myDirective", function() {
    return {
        restrict: 'E',
        scope: {
            buttons: '=buttons'
        },
        templateUrl: "url/to/template"
    }
});

In your index.html file, you should include the directive with the following code snippet:

<my-directive buttons="[
        {
            action: scopeFunction,
            test: 'my text',
            class: 'my-class'
        }
    ]"></my-directive>

Edit: It's not an issue with camel casing as suggested by others here. I have tried using a different name and the directive works fine, it's just the button action that isn't working.

Edit 2: Here is a jsfiddle link I created for better understanding: https://jsfiddle.net/umkzjn42/1/

Answer №1

Make sure to write your directive using camel-case

.directive("myDirective", function() {
    return {
        restrict: 'E',
        scope: {
            buttons: '='
        },
        templateUrl: "url/to/template"
    }
});

Once you have created the directive, you can use it like this

<my-directive buttons="[
    {
        action: scopeFunction(),
        test: 'my text',
        class: 'my-class'
    }
]"></my-directive>

For more information on directives in Angular, check out the official documentation

Answer №2

When creating a directive, make sure to use camel case for the name.

HTML

<my-directive>

JS

.directive("myDirective", function() {}

Another issue in your JSON is that you are using text in the HTML template but passing test in the directive.

There is also a problem with your HTML template where you are passing a function reference instead of calling the function. Use ng-click="button.action()" instead of ng-click="button.action".

Check out the working directive example here

Answer №3

Rename the Directive as myDirective(camelCase) instead of my-directive

.directive("myDirective", function() {
    return {
        restrict: 'E',
        scope: {
            buttons: '=buttons'
        },
        templateUrl: "url/to/template"
    }
});

and then reference it as 'my-directive'

<my-directive buttons="[
        {
            action: scopeFunction(),
            test: 'my text',
            class: 'my-class'
        }
    ]"></my-directive>

Answer №4

<my-component options="[
        {
            action: executeFunction(),
            label: 'click me',
            style: 'button-style'
        }
    ]"></my-component>

It seems like there may be a missing set of parentheses in the function call for defining your action. Hopefully, fixing that resolves the problem.

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

Executing Javascript with Ajax requested data - A guide to making your script run smoothly

Battlefield Page In the graphic provided, there is a battlefield page featuring 20 users. To capture and store this data in a MySQL database, I have created a JavaScript script. However, an issue arises when trying to collect data from the next page after ...

Adjust the appearance of a glyphicon by modifying its color according to various criteria

Using angularjs, I implemented ng-repeat to display details in a table. In the final column, I aim to display the glyphicon 'glyphicon glyphicon-stop' in a specific color. <tr ng-repeat="ps in $ctrl.personLst"> <td>{{ ps.id}}</td& ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

Display a different string from an array at random, revealing each one gradually with a time delay

Looking for a way to display strings randomly without replacing one with another? I need a script that can shuffle words in a list and present them in a random order, with the ability to adjust the delay between each word. If you have a more effective code ...

JavaScript does not function properly on dynamically loaded content from AJAX requests and it is not relying on

I am currently using ajax to load all content from 'mysite/math/' into math.php. I want to render the loaded math content using katex. KaTeX GitHub Inside math.php, I include the Katex library from the CDN mentioned in the link above. The HTML ...

Installing npm displays the command for the successfully installed module, yet no new files are generated

After adding rx-angular to my npm package and successfully installing it locally, I encountered some issues when trying to release it to production. It seemed to partially work but not entirely, leading to confusion due to errors that prompted me to manual ...

I aim to utilize vanilla JavaScript in order to remove the parent element of the button being clicked when the user interacts with it

My latest project involves a meme generator that allows users to input text and images, which are then combined to create a unique 'meme'. Each meme is assigned a unique ID and features buttons for deleting the meme upon hovering. To achieve this ...

Can you explain NodeSource in simple terms, and what purpose does it serve?

Not too long ago, I delved into researching how to effectively host a MEAN stack web application on AWS. During my quest for knowledge, I stumbled upon a tutorial that caught my eye. The one I ended up following can be found at https://www.youtube.com/wat ...

Hide the scroll bar in html/css while keeping the functionality of the arrows intact

Is there a way to remove the scroll bar but still be able to access overflown data using arrows? Any assistance would be greatly appreciated. Thank you in advance. ...

What is the correct way to retrieve a JSON object instead of getting [Object object]?

Creating a basic web scraper integrated with mongoDB. Even though the API returns the JSON object in the correct format, when trying to append it to a bootstrap card on the page, I'm getting [Object object]. Below is my JavaScript code running on th ...

Using the let keyword from another component within the main React application: Helpful tips and tricks

I'm new to React and I want to be able to use the formIsValid state from one component in my main App.js file. When formIsValid is false, I want the DeliveryNote component to be visible, but when it changes to true, I want to hide the DeliveryNote com ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

Struggling to construct a binary tree as my descendants are not arranged in the right sequence

I am currently working on building a binary tree using PHP, MySQL, and a jQuery plugin developed by Frank-Mich. Here is the progress I have made so far... DATABASE STRUCTURE CREATE TABLE IF NOT EXISTS `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, ...

AngularJS 2 treats lists as custom directives

I am working on developing an e-commerce website. The project involves displaying a list of goods and a basket (which contains selected goods). In order to achieve this, I have created a controller with two arrays: one for goods (already filled) and anothe ...

What are the best practices for utilizing ngMousedown effectively?

I've been attempting to capture the ngMousedown event without success. After searching online for a solution, I still haven't found what I'm looking for. Check out this jsfiddle snippet. I've also tried using mouseup and click events. ...

Ways to create a class method to increase a counter?

Can someone help me figure out how to create a custom function or class from the code below? I want to be able to import this module in order to easily increment a count whenever an event occurs in my application. I'm tired of having to manually inpu ...

Selecting radio buttons across multiple div classes

I've been struggling to programmatically select specific radio buttons on a webpage. My goal is to automatically choose the second option in each group of radio buttons, but I'm getting lost in the syntax. Unlike most examples I've found on ...

Exploring the Depths of NodeJS X-Ray Web-Scraper: Uncovering Hidden Gems within Sub Pages

Currently, I am attempting to scrape content using the node.js x-ray scraping framework. While I have successfully retrieved data from a single page, I am struggling with navigating through links and extracting content from subpages simultaneously. Althou ...

Switching Perspective on Live ExpressJS Path -- Node.JS

I previously set up an express route with a template. Here's the code: app.get('/route', function route(req, res) { db.get('db_ID', function compileAndRender(err, doc) { var stream = mu.compileAndRender('theme-file.e ...

Swap Text/Characters When Hovered Over

I'm looking to add a fun interactive element to my webpage where the letters in certain text rearrange when a user hovers over it. For instance, hovering over "WORK" would display "OWKR" instead. I have a feeling that some JavaScript is needed for thi ...