Can functions be passed to an AngularJS directive in a bulk?

I am currently working on a custom dropdown menu directive that allows the attachment of functions to each item in the list. While I know how to pass one function per attribute into the directive, I am curious if there is a way to pass multiple functions instead.

<dropdown items="['item1', 'item2']" actions="['action1()', 'action2()']"></dropdown>

Alternatively:

<dropdown items="[{'item1':action1()}, {'item2':action2()}]"></dropdown>

This would allow for:

<dropdown items="['item1', 'item2']" actions="['action1()', 'action2()']">
    <a ng-click="action1()">item1</a>
    <a ng-click="action2()">item2</a>
</dropdown>

Answer №1

Utilize the = object notation to define the scope when incorporating an array containing objects with specific properties that can be linked to your custom directive.

VIEW DEMO

Controller Section:

 .controller('Ctrl', function($scope) {

    var performAction = function() {
      window.alert(this.label);
    };

    $scope.items = [{
      label: 'Item 1',
      action: performAction
    }, {
      label: 'Item 2',
      action: performAction
    }, {
      label: 'Item 3',
      action: performAction
    }, {
      label: 'Item 4',
      action: performAction
    }];
  })

Custom Directive Setup:

 .directive('dropdown', function() {
    return {
      restrict: 'E',
      scope: {
        items: '='
      },
      template: 
        '<div ng-repeat="item in items track by $index" ng-click="item.action()">' + 
          '<a ng-bind="item.label"></a>' +
        '</div>'
    };
  });

HTML Implementation in index.html:

 <body ng-controller="Ctrl">
    <dropdown items="items"></dropdown>
  </body>

Answer №2

When passing a function to a directive for callback execution, follow the steps below:

  1. Start by using 'return scope' to store the functionName as '&' which is commonly used in passing functions.
  2. When returning it back, ensure the template looks something like this: ng-click='functionName({params:values[,params2:value2]})'

The above method will send the parameters as arguments to the calling controller that invokes the directive.

var app = angular.module('testApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  
  $scope.items=['value1','value2','value3'];
  $scope.items2=['value12','value22','value32'];
  
  $scope.clicked='';
  
  $scope.alert=function(val){
    $scope.clicked=val;
  }
  
   $scope.alerti=function(val){
  $scope.clicked=val+"-Second";
  }
  
});

app.directive('direct', function(){
  return {
        restrict: 'E',
        scope : {
          actionTest:'&',
          tests:'='
        },
       // controller: 'ctrl',
        template: '<ul><li ng-repeat="test in tests" ng-click="actionTest({val:test})">{{test}} </li></ul>'
  }
});
/*
app.controller('ctrl', function($scope){
  
});*/
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="testApp">
<div  ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <p>CLicked : {{clicked}}</p>
    
    <direct tests='items' action-test='alert(val)'></direct>
  
    <!--with a different action function-->
     <direct tests='items2' action-test='alerti(val)'></direct>
 
  </div>
</div>

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

Combine the entities within the object

I need to combine two objects that contain other objects within them, similar to the following structure: let selections = { 123: { abc: {name: 'abc'}, def: {name: 'def'} }, 456: { ghi: {name: ' ...

When a hyperlink is clicked, an image appears in the div

Can someone help me with a javascript method that can display an image in a div based on which href link is clicked? I've started writing some code, but I think it needs further development. <script type=" "> function changeImg(){ var ima ...

Tips on expanding the space between words in a scrolling "marquee" text

Looking for some assistance with my jQuery project involving a horizontal scrolling "marquee" text. I am currently trying to adjust the size of the gap between the phrases in the marquee. Here is an example with the phrase "HEY THERE". jQuery(document ...

Is it possible to use a Backbone Model for an unconventional HTTP POST request that isn't

After going through the documentation at and , I tried to make an HTTP POST request to fetch some JSON data for my model. However, due to the services not being RESTful, I ended up using a POST request instead of a GET request. The code snippet I have co ...

Issue with displaying record attribute as a text variable

I'm currently attempting to retrieve the attribute odata.type from a record so that I can adjust my EditForm based on its value. Strangely, when I utilize a constant to achieve this and print it with console.log, it appears as follows: ƒ HWType(_ref ...

There are currently no articles found that match the search query

Recently, I started working with Django, but I am facing an issue with slug. Whenever I send a request to the Slug, I encounter an error. The error message I receive is: Articles matching query does not exist. Furthermore, I am facing another error while ...

Sending a file using Angular's $http service

I am facing an issue while trying to upload a form with an image file using the angular $http function and multer in the background for receiving. I have successfully uploaded the image via a direct form submission (without angular) as shown below: <fo ...

Importing TypeScript Files without the 'Path' Package Available

After spending a few weeks working on Angular Universal, I've come across a common occurrence where Angular Universal projects have a server.ts file located at the root directory. This server.ts file usually includes imports of various TypeScript pac ...

Tips for building a custom error handling function specifically designed for parsing and handling errors in

Is there a way to reduce redundancy in my code, such as: let name = ""; try { name = data[" "][0][" "][0][" "][0][" "][1][" "][0][" "][1]["C"]; } catch (error) { if (error instanceof TypeError) { console.log("name TypeError"); } } I have consid ...

Using Javascript to dynamically add rows to a table, however they mysteriously appear and disappear soon

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserPermisson.aspx.cs" Inherits="TestProjects.UserPermisson" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" ...

When attempting to use $.ajax to send JSON, it instead sends a query string

I'm having an issue where I'm using ajax to send JSON data with the following script: var sendData = {"test":"opa"}; console.log(sendData); $.ajax({ contentType: "application/json", method: "POST", url: "/test", dataType: "json", ...

Javascript - finding data in a table

I am new to the world of programming and currently learning javascript. I have a table with 754 values in the format 000089/04/18/0601AX. I am looking to create a script that will generate another table containing values with /04/18. Any assistance with ...

Tips for implementing multiple selectors in YUI

Is there a way to use multiple selectors in YUI (YUI 2) similar to jQuery? $('h1, h2, el1, el2, .content, .title').css('color', 'red'); How can I achieve the same in YUI without having to individually add classes using YAHOO ...

Ways to transition into a developer role

I'm currently studying Javascript and Dynamic HTML as part of a course, and while I'm not encountering any errors or warnings in Firefox and Chrome, I believe there might be some issues with my code. If anyone would be willing to take a look and ...

Using jQuery's preventDefault may not be effective in all cases

Within my website, I have implemented a function called showBasket. This function displays a list of items that have been added to a shopping basket whenever a user clicks on a specific link. The menu containing this list hides itself automatically when yo ...

Firestore is refusing to accept a post request made from AngularJS

Trying to upload a new document to the Offers collection using the $http.post method in angularjs, but encountering an error in the console: Error message: Possibly unhandled rejection: { "data": { "error": { &qu ...

Unexpected behavior occurs when ajax is added to an array for jQuery promise results

In my code, I have an each loop that makes individual AJAX requests and stores them in an array like this: var promises = []; $items.each(function(k, v) { promises.push( $.ajax({ url: ..., .... }) ); }); $.when.app ...

Ways to transfer data from one page to another using AngularJS

Hey everyone, I could really use some assistance with AngularJs. My code is quite lengthy, so I have uploaded a document file for you to review. The code snippet below shows my authentication process for email and password. The customerlogin() method retur ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

Divine ListTable - The first row is securely locked, preventing any selection or scrolling

I am a newcomer to blessed and I am encountering an issue with my listTable where the top line does not scroll properly. Any advice on how to rectify this? var blessed = require('blessed'); var screen = new blessed.Screen // Function for genera ...