Utilize a function as a parameter for a directive by calling it from within an

As I continue to enhance my application, I am working on giving a directive the ability to display additional buttons (for various actions) by passing an object to it.

Although I can successfully display the button, I am facing the challenge of executing a function when that button is clicked.

The object itself contains a mix of strings and functions, as shown below:

<tablegrid
  table="flavorings"
  additional-buttons="[{name: 'add', onclick: 'function(){ }', icon: 'fa fa-plus'}]"
  show-actionbutton="true"
  show-rating="true"
  show-search="true"
  show-rowcheckbox="true"
  show-header="true">
</tablegrid>

The template for my directive looks like this:

<button ng-repeat="aB in additionalButtons" class="btn btn-primary" ng-click="ab.onclick" type="button">
  <i ng-class="aB.icon" ng-show="aB.icon  != ''" aria-hidden="true"></i>&nbsp;
  <span>{{ 'TABLEGRID_'+aB.name | uppercase | translate }}</span>
</button>

I am seeking guidance on how to properly execute the onclick function. Can you help me with this?

Answer №1

If you want to call a function from an object within your view, you can do so directly by using the following syntax:

ng-click="yourObject.functionName(parameters)"

Remember to include the parentheses in the function call, even if there are no parameters passed

Below is a demonstration showcasing how this method works:

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

app.controller('MyCtrl', function($scope) {
    $scope.additionalButtons = [
        {'name': 'First', 
         'onclick': function() {alert('1')}
        }, 
        {'name': 'Second', 
         'onclick': function() {alert('2')}
        }
    ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
    <button ng-repeat="ab in additionalButtons" ng-click="ab.onclick()">Click {{ab.name}}</button>
</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

How to access sibling elements within the link function of an AngularJS directive

After extensive searching, I have been unable to find a solution to what seems like a basic question. Even the official documentation did not provide the answer I was looking for. The straightforward question is: how can sibling elements be accessed withi ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

The Autocomplete feature in Material-UI is not rendering any output

Within the render method of a class, an Autocomplete component is causing nothing to appear as rendered; once removed, everything else renders as expected. export default class Home extends Component { render() { return ( ... ...

Incorporate payment processing functionality into your IONIC app by connecting a

Do not flag this question as a duplicate or already answered. If you have knowledge on this subject, please provide an answer. I am attempting to incorporate the payumoney payment gateway into my hybrid app. After following several tutorials, I have resor ...

Return true in an incorrect manner

Coderbyte Challenge 7 Need help with a function that checks if every letter in the string is bounded by '+' signs. The code provided seems to be returning incorrect results - it should return false for the input string below as 'k' is ...

Turn off all pointer events on the overlaying div but keep scrolling enabled

Issue: I am facing a problem with two containers that have overflowing text content like this: https://i.sstatic.net/wsasV.png In this setup, the blue <div>s have overflow:hidden applied. Now, I am trying to synchronize the scrolling behavior of th ...

Send the JSON file to the server by uploading it

Situation Currently, I'm dealing with a page comprising questions structured as shown below: sections:[{ section: 1, questions:[{ question: 1, attachment: [FormData Object] ... }, { question: 2, ...

Transferring information from AJAX to PHP script with the click of a button

Simply put, I am in the process of adding a pop-up update panel to my to-do website using an HTML button. The website already has a login-register system and uses MySQL queries to display different tables for each user. The update buttons on the website c ...

Communication between child and parent components in Vue.js is an essential feature

Attempting to invoke functions from my component to Vue for the login process. This is the code snippet of my component : Vue.component('auths', { data: function() { return { ip: '', sessiontoken: '' } ...

Download the latest Backand Angular SDK from npm

Currently, I have integrated the angularbknd-sdk into my Ionic 1 mobile app. I added it using Bower and then loaded it as an npm module with browserify-shym: In my package.json file "backand": "./bower_components/angularbknd-sdk/dist/backand.min.js" Aft ...

Conceal a div once the user scrolls to a certain position using vanilla JavaScript

As a beginner in the field of web development, I am currently working on creating a blog website. Code Function - One of the challenges I'm facing is implementing a floating pagination bar that needs to be hidden when a visitor scrolls near the foote ...

Reload Popup Box

I am currently developing a website using Django and I am in need of a popup window that can display logging messages and automatically refresh itself every N seconds. In order to achieve this, I am utilizing the standard Python logger, JavaScript, and Daj ...

How to retrieve the first option selected in Material-UI React?

Hey there! I am currently working with React Material UI select. I have a question - how can I set the first option of items as selected without triggering the onChange method? When I change an option, it triggers the onChange method and adds an attribut ...

Utilizing numerous controllers within a single page

I recently decided to organize my angularJS controllers into separate files for better readability. However, I encountered an issue where the controller defined in a separate file is not functioning at all. Could this problem be related to having my MakeGr ...

Can passing undefined to React's setState method be considered incorrect?

Imagine having the following state declared in a React component: const [selectedUsers, setSelectedUsers] = useState<IUser['id'][]>(); This state is being used as the value for a third party HTML <select /> component from Ant Design. ...

React JS: Component failing to render

My react component is not rendering and I can't find any bugs. The problem arises when I set the isLoggedIn state to "true", resulting in my HeroSlide not rendering If isLoggedin = false, then: https://i.sstatic.net/JoDSn.jpg If isLoggedIn = true, t ...

Challenges with the Express server console

I have configured an Express Server and everything appears to be functioning correctly. The content I send is rendered in the browser, and my console.log test statements are being displayed in the terminal. However, when I inspect the browser page, nothi ...

Vue.js 2: Keep an eye on changes, but wait until after the initial data fetch

I recently entered the Vueverse (using Vue.js 2) and I'm encountering some challenges with the watch feature. When the component is mounted, I fetch data from an API and use it to set the value of a radio button. Essentially, I have two radio buttons ...

Before each loop, a return value is encountered

I'm facing a challenge when attempting to sort names in two separate arrays. Once I retrieve the final result, it seems to return the values first before executing the forEach loop. const available = []; const taken = []; const names = d ...

Null value added to MySQL database using Node.js

app.post('/addBeer', (req, res) => { pool.getConnection((err, connection) => { if (err) throw err console.log('connected as id' + connection.threadID) const params = req.body var name = params.n ...