AngularJS directive for attributes. Steps for adding a second attribute directive during compilation phase

I am interested in creating an attribute directive that adds an icon to a button when it is disabled.

Click here to see a similar example on Fiddle

In addition, I would like to include the ng-disabled directive during the compile process (with the value of disabled-button).

What is the most effective approach for this?

When I tried adding the ng-disabled attribute in the compile function, it did not compile. Therefore, if I re-compile my element in the link function, I encounter errors such as having to remove the ng-tranclude directive and triggering events like ng-click twice.

Bonus question: Can I restrict my attribute directive to only apply to html elements like <a> or <button>?

Thank you.

Answer №1

It is not possible to dynamically add directives to the element that contains your directive. This is because the compile function is called after Angular has already processed the element and attached any directives to it. Trying to add another attribute at this stage is too late, as the discovery process has already been completed.

While there may be alternative methods that I am unaware of, I am open to exploring any stable solutions that are not considered hacks.

One suggestion I can offer is to manually include ng-disabled on the button, but let the expression of ng-disabled control your directive, like so:

<button ng-click="ctrl.click()" ng-disabled="ctrl.disabled" disabled-button>

Here is an example of the directive code:

.directive('disabledButton', function($parse) {
    return {
        restrict: 'A',
        transclude: true,
        scope: {
        },
        template: '<span ng-show="disabled">X</span><span ng-transclude></span>',
        link: function (scope, elem, attrs) {
            var disabled = $parse(attrs.ngDisabled);
            scope.disabled = false;
            scope.$watch(
                function() {
                    return disabled(scope.$parent);
                },
                function(newval) {
                    scope.disabled = newval;
                }
            );
        }
    };
})

Check out the Fiddle for a demonstration: http://jsfiddle.net/3orwupo5/1/


Alternatively, you can manually set the disabled property of the button like in this example: http://jsfiddle.net/y5ezvj5L/

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

Using jQuery .css({}) is not causing negative margin to function as expected

$('#thankYouMessage').css({"height": textHeight, "margin-top:": "-52px", "padding-left": "19px"}); The CSS property 'padding-left:' will be applied as expected, but the negative margin will not take effect. The 'margin-top:' ...

Using jQuery to show/hide linked CSS3 animations upon Mouseenter/Mouseleave events

Exploring the capabilities of animate.css and jQuery within a bootstrap environment has been quite interesting for me. However, I've encountered a major issue! I am attempting to trigger animations on mouseenter / mouseleave, which led me to create a ...

Utilizing a combination of PHP and jQuery, certain checkbox options were dynamically deactivated

<input type="checkbox" name="pref[]" value="red//fuji" />Fuji <input type="checkbox" name="pref[]" value="red//pinklady" />Pink Lady <input type="checkbox" name="pref[]" value="red//reddelicious" />Red Delicious <input type="checkbox" ...

Learn how to pass an id from the query parameters to the getInitialProps function in Next.js

Looking to create a basic website that displays content from a database? Utilizing the getInitialProps function from Next.js documentation can help with server-side rendering: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialpr ...

Blue Jay Guarantees: Construct props object on the fly and execute simultaneously

If we take a look at this example: https://github.com/petkaantonov/bluebird/blob/master/API.md#props---promise Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets() }).then(function(result) { console.log(re ...

steps to attach click event to row of a-table component in ant design vue

Here is the code snippet for the table I am working on. I have imported a-table from antd. To enable click functionality to route to a details page from this listing page, an additional td can be added. <a-table :columns="companiesColumns" :d ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

Steps for verifying the existence of a value within an array in relation to another object and generating a new object based on the result

Within my coding realm, I possess an array const dataCheck = ["Rohit", "Ravi"]; In addition to this first array, I also have a secondary array filled with objects const userData = [ { name: "Sagar" }, { name: "V ...

Having difficulty with my async custom react hooks. Is there a way to wait for the result of one hook before using it in another hook?

Having some difficulty working with custom react hooks. I've created 2 custom hooks - one for fetching an ID and another for fetching a profile using the previously fetched ID. Since the second hook is dependent on the ID, I need to await the promise ...

Using a function as a parameter in Typescript: Anticipated no arguments, received 1.ts

I'm encountering an issue when trying to pass the doSomething function into performAction. The error message I'm receiving is Expected 0 arguments, but got 1 interface SomeInterface { name: string, id: string } function doSomethingFunction( ...

Guide to updating information in Firestore using Node.js, embedded in a map array

Encountered an issue with the following error message: Error: Unable to access 'set' property of undefined. I am attempting to update the endTime field in my script for each user, calculate total hours worked, and then update the 'totalTi ...

Unsure of the best way to approach pagination using {$.getJSON, php image array} - seeking guidance on the right

Currently, my code is set up as follows: When a user visits a specific link on the page The $.getJSON function sends a request to a PHP script PHP uses scandir() to generate an array containing image names (eventually in the hundreds to thousands, ...

What is the best way to set up the login page and logged-in homepage using Node, Express, and Passport with the "/" route?

I am currently in the process of developing an application using Node.js, Express.js, and Passport.js. My goal is to create a seamless user experience on the homepage where if you are not logged in, you will see a login form (with potential for additional ...

The controls for the Bootstrap carousel component do not have a clear appearance

Trying to implement a Bootstrap carousel component but facing an issue with the controls not appearing transparent like in the example provided in the Bootstrap documentation. Check out the code snippet: <div class="carousel slide" id="s ...

Error in GatsbyJS: Unable to retrieve data from property 'childImageFluid' due to undefined value

Currently tackling a Gatsby website, but running into an issue: "TypeError: Cannot read property 'childImageFluid' of undefined" Here's the code snippet from my Project.js file: import React from "react" import PropTypes from &quo ...

Merge various observables into a unified RxJS stream

It seems that I need guidance on which RxJS operator to use in order to solve the following issue: In my music application, there is a submission page (similar to a music album). To retrieve the submission data, I am using the query below: this.submissio ...

Exploring Twig variables in Node.js with the node-twig package

Despite following the documentation meticulously, and experimenting with various methods, I am still unable to achieve success. I have attempted using the code snippet below, trying to reference the variable in the main file like this: // None of the opti ...

`What can be done if ng-if is not responding?`

I'm facing an issue where I want to display a link <a href> only when a certain condition is met, but the link doesn't show up as expected. I have already attempted to experiment with changing the position of the code (inside or outside of ...

The contents of the div disappear when using jQuery to extract it from a string

Update: I finally uncovered the reason behind the empty content of the #output div. The content is fetched from the server, which takes some time; by the time the document loads, the div remains empty. Does anyone have suggestions on how to extract infor ...

Javascript unable to access SVG element content on mobile Safari

My approach to reusing certain SVG objects involves defining symbols in an SVG element at the top of my DOM. When I want to display an SVG, I typically use: <svg><use xlink:href="#symbol-identifier" /></svg> For animating SVG's, I ...