The optional attribute feature in Angular directives

Looking for a solution:

angular
  .module('test')
  .directive('multiButton', function () {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        disabled: '@'
      },
      template: '<div class="multi-button"><button ng-disabled={{disabled}}></button></div>'
    });

I'm wondering if there's a way to avoid including "ng-disabled" in the template if the disabled attribute is not present.

Any suggestions on how this can be achieved?

Answer №1

To determine if the attribute is present on a link, and include the associated (ngDisabled) attribute if it is:

angular.module('myApp',[])
    .directive('multiButton', function () {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                disabled: '@?'
            },
            template: '<div class="multi-button"><button></button></div>',
            link: function(scope, element, attr){
                if(attr.disabled){
                    element.find('button').attr('ng-disabled', attr.disabled);
                }
            }
        }
    });

Live Example: http://jsfiddle.net/guv11rxq/

As shown,

<multi-button disabled="hello"></multi-button>
will display:

<div class="multi-button"><button ng-disabled="hello"></button></div>

However, in the absence of the optional attribute,

<multi-button></multi-button>
, it will show:

<div class="multi-button"><button></button></div>

Answer №2

To dynamically control the visibility of elements based on a condition, you can make use of the ng-if directive like so:

 template: '<div class="multi-button" ng-if="disabled != ''"><button ng-disabled={{disabled}}></button></div><div class="multi-button" ng-if="disabled === ''"><button></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

Preventing default action within a passive event listener is not possible because the target is considered passive. This issue is particularly relevant with Three.js Track

I'm currently developing a 3D application using Three.js. One of the key components in this project is implementing a control system for the camera, which I have achieved using TrackballControls. However, as I tried to add an event listener, I encount ...

Decoding a JavaScript object when receiving it as JSON through a POST request

While browsing through various SO posts, I came across the statement "javascript is JSON". However, I am struggling to apply this concept in my application. My issue arises when I try to perform a POST request using jQuery. $.ajax({ type: &apo ...

Ways to verify if a JavaScript file has been successfully downloaded to the client's side

I encountered a strange issue with JavaScript recently. The webpage in question uses jQuery code for collecting data and performing input validation. If the validation passes, it then sends the data to the server. However, some users (around 10% or possib ...

The response from NodeJS is not being properly parsed by Express or BodyParser

const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const adminRoutes = require('./routes/admin'); const shopRoutes = require('./routes/shop'); // app.use(express.u ...

Numerous intersecting lines on display within Google Maps

Currently, I am working on displaying multiple flight routes on Google Maps. I have implemented polylines with geodesic to achieve this functionality successfully. However, a challenge arises when more than two flights intersect the same route, causing o ...

Is there a way to set up automatic switching to a minimized browser window when receiving an alert, even if you are currently using a different window like Outlook or Explorer?

Is there a way to automatically switch to a minimized browser window from a different program window (such as Outlook or Explorer) when an alert is received on a specific tab? I'm looking for a Javascript/Jquery solution. I've attempted the foll ...

Show the user's name in an Express partial once they have logged in

I've been trying to find a solution for my issue without success. Here's the scenario: I have a homepage ('/'), a profile page ('/profile'), and a login/register page. I'm using passport with local, twitter, and google fo ...

Using Angular.js to Make a $http.get Request from a Different Controller

I am utilizing an HTTP resource that provides a JSON list of top 10 entities from a database by calling it in this manner: var filter= "john"; var myApp = angular.module('myApp', []); myApp.controller('SearchController', [&apo ...

Switch classes while navigating within a div

My website has a sticky sidebar with a list of cars and their corresponding categories in a table: <ul class = "cars"> <li class=""><a href="javascript:void(0)" class="model" data-id="1"> BMW </a></li> ...... ...

Unable to launch webpack due to webpack not being detected

When attempting to start webpack, I entered the following command: npm run dev This was done in the command shell where my project and node_modules are located. Upon running the command, an error appeared in the terminal: > clear; npm run --silent so ...

Implementing Google Ads Code in NextJS for Automated Units

I'm currently working on a NextJS project and I need to integrate the Google AdSense code for automatic ads. The Google ad code I have is: <script async src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env. ...

One way to choose an element based on its class name with jqLite

I am currently working on optimizing my Angular.js app by removing jQuery and replacing it with Angular's jqLite in order to reduce the app's weight. However, I have run into a challenge as my app heavily relies on using find('#id') and ...

AngularJS Date Formatting

I am facing an issue with binding a simple date object created in JavaScript to an input control using AngularJS. It seems like the problem might be related to the format of the date. Can you please help me understand why this happens? This problem specifi ...

Notification of Leaf Name in d3.js

I am trying to display the leaf name when it is clicked, but I am unsure how to do it. I am new to D3 and would appreciate any guidance on how to achieve this. Source: http://bl.ocks.org/mbostock/7607535 var circle = svg.selectAll("circle") .data(nod ...

Switching between two states of a single 'td' element within a column

I am trying to implement a feature where only specific elements in the fourth column of a four-column table toggle when clicked. For example, clicking on an element in the fifth row third column should toggle the corresponding element in the fifth row four ...

When using the jQuery datepicker with the minDate set to 0, any past dates entered in the text box will be automatically reset to the current date

How can I prevent users from selecting past dates in a jQuery datepicker, while keeping any existing past dates displayed as is? My current code looks like this: $("#t1").datepicker({ minDate:0 }); And the text box code is, <input type="t1" va ...

Unable to retrieve data from the database within PHP code

I have successfully built a shopping cart website utilizing SQL, HTML, and PHP. Below is the code snippet for the 'Add to Cart' button: <form method="post" action="cart.php" class="form-inline"> <input type="hidden" value="&apos ...

Using `ngRepeat` on a different array of values for repetition

Working with AngularJS. Here is an example of a JSON object: "skills": { "Charisma": {}, "Dexterity": { "Sk3": [ [ true, true, true, true, false ], 44 ] }, ... And the corresponding HTML: <div class="pan ...

React.js: Passing an array as a property to an element results in the transformation of the array into an object

I'm trying to understand why passing an array as a prop to another element results in it getting transformed into an object with the array as its value. I need help understanding if this is a common JavaScript 'quirk' or specific to React an ...

Tips for sorting ng-Table using an array of numerous values

I am currently working on implementing angular-selectize.js (https://github.com/machineboy2045/angular-selectize) into my project. This will create a search box that allows for entering multiple values to filter all cells in an ng-Table without the need to ...