Child component being disabled by parent component using ng-disabled

While I'm delving into Angular js v1.5, I'm taking the opportunity to experiment with components. In this endeavor, I've come up with 2 components:

  • A circular button, aptly named "circular button".
  • A component that encapsulates a circular button and a text field, known as "counter button". This component serves to display a counter alongside the circular button, akin to the 'like' or 'dislike' buttons on YouTube.

Here's the template code for the circular button:

<button
    class="circular-button {{ $ctrl.config.color }}"
    ng-click="$ctrl.onClick()">
    {{ $ctrl.config.text }}
</button>

Definition code for the circular button component:

components.component('circularButton', {
    bindings: {
        onClick: '&',
        config: '<'
    },
    templateUrl: '/views/components/photos-circular-button.html'
});

Template code for the "counter button" component:

<span>
    <circular-button
        config="$ctrl.buttonConfig"
        on-click="$ctrl.action()"></circular-button>
</span>
<span>{{ $ctrl.counter }}</span>

And the component definition code for it:

components.component('counterButton', {
    bindings: {
        onButtonClick: '&',
        counter: '<',
        buttonConfig: '<'
    },
    templateUrl: '/views/components/photos-counter-button.html',
    controller: function () {
        var ctrl = this;
        ctrl.disabled = false;
        ctrl.action = function () {
            ctrl.counter++;
            ctrl.onButtonClick();
        }
    }
});

The general behavior dictates that when the button is clicked, the counter increments by 1. Currently, the parent component, "counter-button," passes a function to execute upon clicking the circular button, utilizing the bindings property as such:

onClick: '&'

This way, the parent component injects the function to be executed. I've followed the Angular Component documentation found here under the "Example of a component tree" section.

Thus far, everything is functioning smoothly. However, I aim to enhance the component by having the circular button disable after being clicked, allowing a user to increment the counter only once. Similar to the behavior of the 'like' button on a YouTube video.

To implement this, I attempted to add the ng-disabled directive to the counter-button template as follows:

<span>
    <circular-button
        config="$ctrl.buttonConfig"
        on-click="$ctrl.action()" ng-disabled="$ctrl.disabled"></circular-button>
</span>
<span>{{ $ctrl.counter }}</span>

Additionally, I incorporated the following line of code in the component controller:

controller: function () {
    var ctrl = this;
    ctrl.disabled = false;
    ctrl.action = function () {
        ctrl.counter++;
        ctrl.disabled = true; //NEW LINE OF CODE.
        ctrl.onButtonClick();
    }
}

Nonetheless, this approach failed as the ng-directive applies to the

<circular-button></circular-button>
element rather than the button within it, resulting in the expected outcome.

As a result, I am contemplating ways to disable the button from the parent component (or any client using the circular button) without introducing another binding to maintain the circular button's generic nature. Your suggestions and insights on alternative methods would be greatly appreciated. Thank you in advance!

Answer №1

This solution doesn't exactly propagate the ng-disabled attribute down, but I stumbled upon your question while tackling a similar issue. What I ended up doing was creating bindable properties in each component to handle the "isDisabled" flag.

For example:

app.component('outerComponent', {
  controller: (function() {
    function OuterController() { this.myOuterDisabledProperty = false }
    return OuterController;
  })(),
  templateUrl: 'outerComponent.html',
  bindings: { myOuterDisabledProperty: '=' }
});

app.component('innerComponent', {
  controller:(function() {
    function InnerController() { this.myInnerDisabledProperty = false }
    return InnerController;
  })(),
  templateUrl: 'innerComponent.html',
  bindings: { myInnerDisabledProperty: '=' }
});

...and the template would look something like this:

<div style="background-color: #eee; padding: 10px">
  <h2>Outer Component - disabled: {{$ctrl.myOuterDisabledProperty}}</h2>
  <inner-component my-inner-disabled-property="$ctrl.myOuterDisabledProperty"></inner-component>
</div>

Check out this live example for a demonstration: https://embed.plnkr.co/2gbAGd1PM9Gx5rslXChB/

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

Accordion menu designed exclusively with JavaScript

Implementation of required menu structure: Main Menu Submenu Contacts News Photo Submenu Submenu Submenu Main Menu Main Menu Main Menu When clicking on the "Main Menu" button, a list of "Submenu" elements opens. Clicking on the "Submenu" button ope ...

Activating a hyperlink within a Div element by clicking on the Div itself

In my card element, I have a link that, when clicked, opens a modal pop-up containing all the necessary project information. I am currently attempting to trigger a click event on that link whenever any part of the div is clicked. This task is for a school ...

Specify that a function is adhering to an interface

Is there a way in Typescript to ensure that a function implements a specific interface? For example: import { BrowserEvents, eventHandler, Event } from './browser-events'; export function setup(){ const browserEvents = new BrowserEvents(); b ...

Ensure that all items retrieved from the mongoDB query have been fully processed before proceeding further

In the midst of a challenging project that involves processing numerous mongoDB queries to display data, I encountered an issue where not all data was showing immediately upon page load when dealing with large datasets. To temporarily resolve this, I imple ...

How do I ensure the CSS triangles maintain their correct boundaries when hovered over with the cursor?

Can the issue of incorrect triangle activation be fixed when hovering on http://jsfiddle.net/2AXhR/? Sometimes the wrong triangle is triggered due to the triangles' bounding areas being rectangles, causing overlap and z-index conflicts. <style ...

What are the potential reasons for a "child-removed" event failing to trigger?

Let's look at a simplified version of the code: var queueTask = function (taskObject) { var deferred = $q.defer(); // Creating a new task reference & pushing a new Task object to that location var newTaskRef = firebase.database().ref ...

My objective is to show the div element just once using AngularJS

Here's the scenario I want to show this div just once, not multiple times: //angular js code $scope.arr=["sunday","mpnday","tuesday"]; //html view <ul> <li ng-repeat="x in arr"> <div><p>{{ x }}</p> </div> & ...

Passing props down in Next.js when working with children components

Within my Next js page, I have a component structured as follows: ... <Chart isShoppingChartOpen={isShoppingChartOpen} toggleShoppingChart={toggleChartVisibility} lineItems={lineItems} /> <main className= ...

Check Image Dimensions prior to Image Loading

I've been working with JQuery Masonry and would like to incorporate Lazy Load using a WordPress plugin to load images only when they come into view. The issue I'm facing is that when Lazy Load is used, the masonry elements don't recognize t ...

Filter a div based on multiple conditions using JavaScript/jQuery

In my filtering system, I have two sections: place and attraction. When I select a place, the corresponding div is displayed according to the selected place. Similarly, when I select an attraction, only the attractions are filtered accordingly. <ul clas ...

Add a pair of assorted div elements to a shared container

I have two different sections with classes named "red" and "blue". By default, these sections are hidden. I want to duplicate them and display them in a single container named "cont". The red button appends the red section and the blue button appends the b ...

What is the best way to insert a React component or raw HTML into another React component?

Dealing with raw HTML markup returned from an AJAX call can be tricky in React. I've tried using dangerouslySetInnerHTML, but React just throws errors when I do. It's like trying to navigate through a maze. After some trial and error, I decided ...

What are the steps to successfully implement "Pointermove" event delegation in Safari iOS for parent/child elements?

I've encountered an issue that I'm struggling to find a solution for. My goal is to implement an event delegate using pointermove on a parent container, and I need to be able to detect when the event transitions between a child element and the pa ...

When using Angular, the function `$window.location.assign` does not properly load within a controller when trying to

After implementing $window.location.assign('#/someurl'); in a controller, the URL hashtag updates but fails to load. .when("/signin", { templateUrl: templateSource+"/signin", controller: function($scope, $location, $window){ ...

Is using selectors a more effective way to retrieve computed data compared to using class methods?

When using react, redux, and reselect in a project, is it preferable to move all computable data from class methods to selectors and avoid mixing the use of both? Are there different concepts behind these approaches? class DocsListView { getOutdatedDocs ...

Utilizing JQuery Ajax to Retrieve Conversion Explanations

In my project, I have a set of AJAX wrapper functions that I use to make AJAX requests. I am now considering switching to using the Fetch API instead. As a newcomer to this transition, I have some questions and concerns that I think will be beneficial for ...

Passing an array from JavaScript to PHP and then storing it as a .json file

Query I am trying to pass an array to PHP and save it in a data.json file. However, the data.json file is being created but showing Null as output. I have spent about 2 hours on this code, checked numerous solutions on SO, but nothing seems to work. As I ...

Forward the value of the selected radio button

Currently, I am focusing on this code snippet. <html> <script> var submit = document.getElementById('btnFormSubmit'); submit.addEventListener('click', submitForm); function submitForm(event){ event.preventDefault(); event. ...

If I change the request mode to 'no-cors' in my Firebase cloud function, how will it impact the outcome?

After encountering an issue with the Firebase inbuilt password reset functionality, I created a Firebase function to handle OTP verification and password changes based on the correctness of the OTP. The function is designed to validate the OTP provided, ch ...

Issues with pop-up windows on YII2 gridview

I am currently developing a web application using the Yii2 framework for my company to efficiently manage their storage. I have incorporated various plugins from kartik-v to enhance the functionality of the application. However, I am facing an issue with i ...