Customizing AngularJS directives by setting CSS classes, including a default option if none are specified

I have designed a custom directive that generates an "upload button". This button is styled with bootstrap button CSS as shown below:

<div class="btn btn-primary btn-upload" ng-click="openModal()">
  <i class="fa fa-upload"></i> Upload
</div>

How can I overwrite the CSS classes and default to btn btn-primary btn-upload if no override is specified? The aim is to use the same directive across the app, where in some instances it functions as a button and in others as a basic unstyled link.

This is what my directive code looks like:

'use strict';

    angular.module('documents').directive('documentUpload', ['$timeout', '$translate', '$q', '$docs',
      function ($timeout, $translate, $q, $docs) {
        return {
          restrict: 'E',
          scope: {
            text: '@',
            refId: '@',
            refType: '@',
            documents: '='
          },
          templateUrl: 'modules/documents/views/directives/document-upload.html',
          controller: function ($scope, $element) {

            // Need help overriding CSS here

            $scope.openModal = function() {

              $docs
                .openModal({ 
                  documents: $scope.documents,
                  refId: $scope.refId,
                  refType: $scope.refType
                })
                .result.then(function (result) {
                  // TODO 
                });

            };

          }
        };
      }
    ]);

Answer №1

One possible solution is:

<div class="{{ btnClass || 'btn btn-primary btn-upload'}}" ng-click="openModal()">
  <i class="fa fa-upload"></i> Upload
</div>

Subsequently, you can create the directive as follows:

angular.module('documents').directive('documentUpload', ['$timeout', '$translate', '$q', '$docs',
  function ($timeout, $translate, $q, $docs) {
    return {
      restrict: 'E',
      scope: {
        text: '@',
        refId: '@',
        refType: '@',
        documents: '=',
        btnClass: '=' //** new attribute here
      },
      templateUrl: 'modules/documents/views/directives/document-upload.html',
      controller: function ($scope, $element) {

        $scope.openModal = function() {

          $docs
            .openModal({ 
              documents: $scope.documents,
              refId: $scope.refId,
              refType: $scope.refType
            })
            .result.then(function (result) {
              // TODO 
            });

        };

      }
    };
  }
]);

For a simplified demonstration, visit this link: http://jsbin.com/qosiquteli/edit?html,js,output

Answer №2

To customize the div's appearance based on a defined class attribute, follow these steps:

 angular.module('documents').directive('documentUpload', ['$timeout', '$translate', '$q', '$docs',
      function ($timeout, $translate, $q, $docs) {
        return {
          restrict: 'E',
          scope: {
            text: '@',
            refId: '@',
            refType: '@',
            documents: '='
          },
          templateUrl: 'modules/documents/views/directives/document-upload.html',
          link: function (scope, iElement, iAttrs){
             if (iAttrs.class) {
                iElement.find("div").first().attr("class", iAttrs.class);
             }
           },
          controller: function ($scope, $element) {

            // Any CSS modifications can be made here

            $scope.openModal = function() {

              $docs
                .openModal({ 
                  documents: $scope.documents,
                  refId: $scope.refId,
                  refType: $scope.refType
                })
                .result.then(function (result) {
                  // Implementation of any necessary functionality
                });

            };

          }
        };
      }
    ]);

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

Is it possible to precisely position multiple children in a relative manner?

I am currently developing a custom dropdown menu where I want the parent element to be relatively positioned within the page. The goal is for all the child elements of the dropdown menu (the list items) to appear as if they are part of a select element and ...

How come the array's length is not appearing on the browser screen?

Code: initialize: function() { this.todos = [ {id: 100, text: 'Rich'}, {id: 200, text: 'Dave'} ]; }, activeTodos: function() { this.todos = this.todos.length(function() { return this.todos; }); ...

Next.js Error: The text displayed on the page differs from the HTML rendered by the server

Currently, I am facing an issue with the error "Error: Text content does not match server-rendered HTML." Here is my scenario - I have received a dateTime from an API, for example '2022-12-25T11:22:37.000Z', and I want to display it on a compone ...

Adding fresh data to an array in mongoose

How can I insert new values into a MongoDB database? Currently, the Grocery Schema contains an array of users in which I want to store all user IDs related to itemName. However, I'm unsure about how to accomplish this. var mongoose = require('mo ...

Every time I attempt to submit the login form on the Ionic and Angular page, instead of capturing the values of the form group, the page simply refreshes

Struggling with submitting the login form in Ionic and Angular? When attempting to submit, the page reloads instead of capturing the form group values. I am utilizing angular reactive forms and form builder within the ionic framework. Need assistance in id ...

Guide to successfully navigating to a webpage using page.link when the link does not have an id, but is designated by a

This is my current code snippet: async function main(){ for(int=0;int<50;int++){ const allLinks = await getLinks(); //console.log(allLinks); const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPa ...

Error encountered while rendering ngMessages error in AngularJS due to ngif markup issue

I am currently utilizing ngMessages to validate a dynamically generated form using ngRepeat. While ngMessages is functioning as expected, I want the validation error messages to only display when the submit button is clicked. To accomplish this, I am emplo ...

Unable to disable background color for droppable element

For my project, I am working with two div boxes. My goal is to make it so that when I drag and drop box002 into another div box001, the background color of box001 should change to none. I have attempted to achieve this functionality using jQuery without s ...

Can anyone point out where the mistake lies in my if statement code?

I've encountered an issue where I send a request to a page and upon receiving the response, which is a string, something goes wrong. Here is the code for the request : jQuery.ajax({ url:'../admin/parsers/check_address.php', meth ...

Leveraging electron-usb alongside electron

I attempted to integrate the electron-usb library into my electron project. Upon running npm start with require('electron-usb') in my index.html file, an error is displayed in the console: Uncaught Error: The specified procedure could not be fo ...

Unable to allocate a second item to an existing one

Encountering an unusual issue while trying to assign an item a second time. Initial scenario: I am working with a jqxTree containing various items as shown below: - apple - oracle - microsoft When I drag and drop one item into another, the structure loo ...

using jquery to retrieve the current time and compare it

This is the code I currently have: var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() aler ...

What could be causing the continuous occurrence of the error message stating "Module 'socket.io' cannot be found"?

For the past few days, I've been attempting to incorporate socket.io into my NodeJS script. However, every time I run it, I encounter the frustrating error message stating "Cannot find module 'socket.io'". The detailed error is as follows: ...

Leveraging an AngularJS variable within an iframe

Is it possible to use a variable inside an iframe src or ng-src attribute? I've tried different variables but none seem to be recognized. For example: <iframe ng-src="http://www.example.com/?name={{test}}"> </iframe> The variable test ju ...

Managing configuration variables in ExpressJS for various environments

Is it possible to set a variable for different environments when defining the environment? app.configure 'development', () -> app.use express.errorHandler({dumpExceptions: true, showStack: true}) mongoose.connect 'mongodb://xxx:<a h ...

Explore additional sub-categories by clicking on them with the help of jQuery or alternate techniques

I am currently working on a Magento store that has Categories with an overwhelming amount of sub-categories, taking up almost half of the page. I want to enhance user experience by implementing a feature that displays a "Load more" button when there are mo ...

Issues with jQuery .click and .html functions not functioning as expected

Does anyone have experience creating a game with jQuery? I can't seem to get the options after the first choice to work. Sorry, I don't have a working example at the moment. --- jQuery --- $(document).ready(function() { $(".console"). ...

Experiencing difficulties with the ng-click directive in AngularJS

Trying to solve a coding dilemma with two buttons - one that triggers a click event redirecting to the login page, and another button meant for displaying a pop-up. Strangely, clicking on the second button also ends up directing me to the login page. This ...

Performing a consistent influx of data into a MySQL database using Node.js encounters an issue: "Unable to enqueue Handshake as a Handshake has

I am trying to insert values into a database in a continuous manner. Here is the code I have attempted: var mysql = require("mysql"); const random = require("random"); var con = mysql.createConnection({ host: "xxx", user: "xxx", password: "xxx", ...

What is the best way to position my NavBar items to the right using the Bootstrap v5.2 framework?

I am working on a project for my course and need some help. My goal is to have the brand stay aligned to the left, while other items align to the right. I have been able to achieve this without a toggler using justify-content-end, but with a toggler, I a ...