What is the best way to implement a unique function in an angularjs directive?

Is it possible to execute a custom function when clicking on the checkbox of a table row shown below? I am using the Angular Smart Table directive and need to be able to store the rowid or another property of the rows when the checkbox is clicked.

app.directive('csSelect', function () {
    return {
        require: '^stTable',
        template: '<input type="checkbox"/>',
        scope: {
            row: '=csSelect'
        },
        link: function (scope, element, attr, ctrl) {

            element.bind('change', function (evt) {
                scope.$apply(function () {
                    ctrl.select(scope.row, 'multiple');
                });
            });

            scope.$watch('row.isSelected', function (newValue, oldValue) {
                if (newValue === true) {
                    element.parent().addClass('st-selected');
                } else {
                    element.parent().removeClass('st-selected');
                }
            });
        }
    };
});

EDIT

This directive can be used as follows:

<td cs-select="row"></td>

If I add ng-click to the td element to check for a clicked row, clicking anywhere inside the td element will act as clicking on the row. This does not solve the issue regarding the checkbox behavior.

Answer №1

app.directive('csSelect', function () {
    return {
        require: '^stTable',
        template: '<input type="checkbox"/>',
        scope: {
            row: '=csSelect',
            myFunc: '&cs-func'
        },
        link: function (scope, element, attr, ctrl) {

            element.bind('change', function (evt) {
                scope.$apply(function () {
                    ctrl.select(scope.row, 'multiple');
                });
            });

            scope.$watch('row.isSelected', function (newValue, oldValue) {
                if (newValue === true) {
                    element.parent().addClass('st-selected');
                    scope.myFunc();
                } else {
                    element.parent().removeClass('st-selected');
                }
            });
        }
    };
});

afterward

<td cs-select="row" cs-func='alert("hello")'></td>

Answer №2

Include the ng-click directive in the template of the directive.

template: "<input type='checkbox' ng-click='myFunction()'/>"

Then, within the link or controller function of the directive:

scope.myFunction = function() { //Your code here };

Answer №3

To incorporate functions into your template HTML within your directive, simply include them in the scope parameter provided to your link function.

This method can be utilized for your change handler, and you can apply ngClass to determine whether a specific CSS class should be attached to your input element.

Consider implementing something similar to the following:

return {
  // ...,
  template: '<input ng-change="changeHandler()" ng-class="{'st-selected': row.isSelected}">',
  link: function (scope, elem, attrs, parentCtrl) {
    scope.changeHandler = function () {
      // parentCtrl.whatever(scope.row);
    };
  }
};

An essential addition that your input field lacks is an ngModel. While not fully comprehending the inner workings of your stTable directive, it is advisable to bind your checkbox directive to a model, such as row.isSelected.

Answer №4

Experiment with this:

ng-controller="app.controller()"

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 trigger a hover effect on a div and its child simultaneously using HTML and jQuery

Here's my concept: I want the text to be contained within div elements with an integrated image, rather than just having fading in and out pictures. Here's my attempt: #first{ position: absolute; } #second{ position: absolute; -we ...

The issue with implementing simple getElementsByClassName JavaScript in the footer of a WordPress site persists

I am facing an issue with a 1-liner JavaScript code in the footer where getElementsByClassName function doesn't seem to work for tweaking style attributes. The text "Hello World" is displaying fine, so I suspect it might be a syntax error? Here' ...

Remove inline CSS from HTML elements

Having a large HTML file structured like this: <div style="min-height: 32px; padding: 5px; width: 800px; margin: 50px auto; overflow: auto; font-size: 12px;" class="selectable clearfix selected_layer" id="wrap"> <div class="selectable" id="l1" st ...

Guide on utilizing exported API endpoint in Node and Express

Seeking a deeper understanding of express and its utilization of various endpoints. Recently came across an example of an endpoint that reads in a json file, demonstrated as follows: const fs = require('fs'); const path = require('path&apos ...

Evaluate the script based on the number of words, not the number of characters

I have encountered an issue where I am only able to count the characters of a content, but what I really need is the word length. Specifically, I want the CSS to take action when there are words of 20 characters, but not if those 20 characters consist of m ...

Unable to bind click eventListener to dynamic HTML in Angular 12 module

I am facing an issue with click binding on dynamic HTML. I attempted using the setTimeout function, but the click event is not binding to the button. Additionally, I tried using template reference on the button and obtaining the value with @ViewChildren, h ...

Accessing the current instance in Vue when triggered by a checkbox event

Recently, I tested out a to-do-list application built in Vue that has a checkbox feature to mark completed items. I'm looking for a way to access the current instance from the checkbox event. Here's what I've accomplished so far: myObject ...

Streamlining the Process of Uploading Files using Selenium WebDriver

My current project involves automating the uploading of an HTML file. Unfortunately, the website I am working on has made this task more complicated than necessary. The code for the file upload section is as follows: <div class="form-row"> < ...

Struggles encountered when choosing the initial visible item

I have a set of 3 tabs, each with its own heading and content. However, I only want to display the tabs that the user selects by checking the corresponding checkboxes. There are 3 checkboxes, one for each tab. Below is the code snippet: //Function to ...

Utilizing Selenium and Protractor for efficient text entry with the ng-model locator

I am using Selenium and Protractor to input text into text fields located by Angular locators. However, after I enter the text, the field does not immediately display the entered text until I click on it again. Essentially, it is not dynamically refreshin ...

"Although all error messages are functional in Postman, they are not appearing correctly on the frontend client

I am currently developing a website using React and Node. While testing my register and login functionality in Postman, I encountered an issue where the error message for login (e.g., user doesn't exist, username or password incorrect) is not displayi ...

When an image is clicked, I am attempting to access data from a Sharepoint list

In my Sharepoint list, there are three columns: Image, Title, and Description. I am using ajax to retrieve the items from the list. The images can be successfully retrieved, but my goal is to display the title and description of the clicked image when an ...

Changing a date string to MM DD format in React without using plain JavaScript

I'm familiar with how to handle this outside of React. My issue is that I have a date string coming from an API within an object, and I need to reformat it. The current format is "2022-12-13T06:00Z" but I want it to display as "December 13". The objec ...

Incorporate additional text to the downloads hyperlink using jquery

Is it possible to achieve this using jQuery since I am unable to directly modify the HTML markup? I am looking to append download.php?file= to a URL without replacing the entire href attribute. Here's an example of what I'm trying to achieve: & ...

jQuery slider - display unlimited images

Currently, I am encountering issues with a Flickity carousel of images. When an image/slide is clicked, a modal window opens to display a zoomed-in version of the image. The problem arises when there are more or fewer than 3 images in the slider — my cod ...

Using Props with jQuery in React Components: A Comprehensive Guide

I trust you comprehend this straightforward example. I attempted to modify the background color of my HTML element during initial rendering by managing it in a React Component with a touch of jQuery assistance. Here is the code within my React Component ...

Error during the production build of Next.js Internationalized Routing: Prerendering page encountered an unexpected issue

The configuration in my next.config.js file looks like this: module.exports = withBundleAnalyzer({ i18n: { locales: ['en', 'es'], defaultLocale: 'en', localeDetection: false, }, ... }); This setup allows for ...

Utilize AJAX and JavaScript to retrieve file information and facilitate file downloads

I have developed a script that intercepts Captcha form submissions. Typically, when the form is submitted, a file will be downloaded (such as exe or zip) in the usual way where it appears at the bottom of the Chrome browser and gets stored in the "download ...

Arrange the JSONB data type with sequelize literal in your order

My current approach involves querying for all items using the following structure: const filteredItems = await allItems.findAll({ where: conditions, include: associations, order: sortingCriteria, limit: limit, o ...

When using Google Maps in an Android webview, an error occurs stating that the user has denied geolocation

I'm having trouble loading Google Maps v3 (Javascript) in an Android web view An error keeps occurring: User denied geolocation Using Ionic, it works flawlessly in desktop Chrome (ionic serve) and iOS devices. The error only appears on Android. ...