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

Concerns regarding code coverage when testing asynchronous functions using nockjs and jest

In my latest project, I've created a basic unit test for making API calls using NockJS and Jest within a React application. Here's a snippet of the code: AjaxService.js export const AjaxService = { post: (url, data, headers) => { ...

How can I make my div disappear when I click outside of it using jQuery? I am finding the solution on Stack Overflow to be confusing

Utilizing jQuery to conceal a DIV upon clicking outside of it Although I've heard positive feedback about this method, I'm uncertain about its functionality. Can someone provide an explanation? I understand that .has() identifies elements contai ...

Unable to append a property to each object within an array during a loop

Hey everyone, I could really use some help with this problem I'm facing. Let me explain what's going on - I'm working on pulling documents from MongoDB using Mongoose. Take a look at the array of objects that is returned from the mongoose qu ...

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 ...

What are the steps for implementing Babel in a CLI program?

Currently, I am working on developing a CLI program in Node using Babel. While researching, I came across a question on Stack Overflow where user loganfsmyth recommended: Ideally you'd precompile before distributing your package. Following this ad ...

JSON has difficulty retaining the value of the variable

I've been working on a piece of code that scans through a directory, extracts each file's name and content. The aim is to retrieve the data from these files, usually consisting of numbers or short pieces of text. var config = {}; config.liveProc ...

What is the method to execute a prototype function within another prototype?

I am facing an issue with my JavaScript class and need some help to resolve it. MyClass.prototype.foo = function() { return 0; } MyClass.prototype.bar = function() { return foo() + 1; } Unfortunately, when I try to run the program, it throws an ...

Setting up SKPM (Sketch Plugin Manager) using npm

I've been trying to install a specific npm package, but I keep encountering numerous errors that are unfamiliar to me. It's important to note that these errors occur after running the command sudo npm install -g skpm: gyp ERR! configure error g ...

Modifying JavaScript Objects

After referring to the discussion at , I encountered a challenge with my javascript ajax function that retrieves JSON data. My goal is to trigger different js events based on the key-value pairs of the JSON response, but unfortunately, I am facing diffic ...

React - The `component` prop you have supplied to ButtonBase is not valid. Please ensure that the children prop is properly displayed within this customized component

I am attempting to use custom SVG icons in place of the default icons from Material UI's Pagination component (V4). However, I keep encountering this console error: Material-UI: The component prop provided to ButtonBase is invalid. Please ensure tha ...

Fill a dropdown menu with options from a JSON object, arranging them in ascending order

I have a JSON hash that I am using to populate a combo box with the following code: $.each(json_hash, function(key, value) { $("#select").append("<option value='" + key + "'>" + value + "</option>"); }); The functionality w ...

Is it possible to transform a webpack configuration into a Next.js configuration?

i have come across a webpack configuration setup from https://github.com/shellscape/webpack-plugin-serve/blob/master/recipes/watch-static-content.md: const sane = require('sane'); const { WebpackPluginServe: Serve } = require('webpack-plugin ...

Creating a gaming application with Phaser.js and Ionic with subpar rendering capabilities

Attention developers! I recently created a game app using Phaser.js. I integrated the code into an Ionic blank starter app, allowing the Ionic framework to render the view while Phaser takes care of displaying the game. Issue: The game is a simple flapp ...

"The AJAX response returned a status code of 200, however, the PHP script being executed on the XAMPP localhost did not provide

The HTML code initiates a localhost function called getNodes which returns JSON data that is verified by JSON lint. However, when the same function is invoked using AJAX from a JavaScript file, a 200 response code is received without any response data. I h ...

Is it possible to manage the form submission in React after being redirected by the server, along with receiving data

After the React front-end submits a form with a POST request to the backend, the server responds with a JSON object that contains HTML instead of redirecting as expected. How can I properly redirect the user to the page received from the server? For inst ...

The voting system will increase or decrease by 1 to 5 during each round

Recently, I added a voting system to my website inspired by this source. It's functioning well, but there is an issue where each vote can sometimes count for more than one. You can view the source code on the original website and test it out live here ...

Prevent the creation of nested objects in Django Rest Framework

Hello there, I need assistance on how to prevent the creation of nested objects within my serializers. Here is an example of my serializer setup: class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = (&a ...

Executing a time-consuming function call within the componentDidMount lifecycle method of a React component

When working with my React component, I utilize the componentDidMount function to pass a string received through props to a processing function. This function then returns another string which is used to update the component's state. import React, { C ...

How to make an Ajax "POST" request to the server using jQuery or AngularJS without sending any parameter data

"Execute a 'POST' request to the server by using the code provided below However, the parameter data is not being sent to the server. I have attempted both the jQuery Way and var request = $.ajax({ url: baseUrl, type:'post', da ...

Is there a way to adjust the height of one div based on the height of another div in Bootstrap?

I am experimenting with a Bootstrap example featuring a table in the left column and 4 columns in 2 rows in the right column. Check out the code below: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css ...