Is it possible for me to transfer a class attribute to a directive template in AngularJS?

I recently came across this directive in AngularJS:

productApp.directive('notification', function($timeout) {
    return {
        restrict : 'E',
        replace : true,
        scope : {
            type: "@",
            message: "@"
        },
        template : '<alert class="alert alert-type">message</alert>',
        link : function(scope, element, attrs) {
            $timeout(function() {
                element.hide();
            }, 3000);
        }
    }
});

This allows me to call it from the view like so:

<notification type="alert.type" message="alert.msg"></notification>

In my controller, I have the alert object defined as follows:

$scope.alert = { type : 'success', msg : 'This is a test'};

I was wondering how I can pass the type dynamically. I tried doing that, but it didn't seem to work. When I pass "alert-success" to the directive, it works fine, but I want it to be dynamic. Is there a way to achieve this?

Thank you.

Answer №1

Consider updating the directive with this code:

productApp.directive('alertMessage', function($timeout) {
    return {
        restrict : 'E',
        replace : true,
        scope : {
            type: "=",
            message: "="
        },
       template : '<alert class="alert alert-{{type}}">{{message}}</alert>',
        link : function(scope, element, attrs) {
            $timeout(function() {
               // element.hide();
            }, 3000);
        }
    }
});

When using isolated scope, utilize = to connect parent scope properties

See a demonstration on Fiddle

Answer №2

Within your link function, you have the ability to access the values passed into your directive by using attrs.type and attrs.msg.

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

Make sure to use dispatch when updating the array to prevent any potential infinite loops

I am currently working with JSX to create a function that reads user profiles and updates them upon clicking a button. The object userProfiles contains existing user profile data, which should be updated by combining the current contents with those from ne ...

Enhancing React URLs

Our company deals with URLs in this format: http://helloworld.com/product?filter[category][0]=persian We aim to transform the URL into a cleaner version: http://helloworld.com/product-persian When additional filters are added to the current UR ...

"Utilize AngularJS JavaScript to nest HTML elements within each other for dynamic web

I have developed a unique custom directive called hero. My goal is to set up a nested view for multiple instances of hero. Check out this demo to see it in action. The desired layout looks something like this: <hero a="1"> <hero a="2"> ...

Ways to extract the value from a jQuery object

How can I retrieve the selected time value using a jQuery plugin and save it on a specific input element within the page? Refer to the plugin and code provided below: http://jsfiddle.net/weareoutman/YkvK9/ var input = $('#input-a'); input.cloc ...

Content Security Policy Error triggered by Iframe Source Running Script in Web Extension

My web extension for Firefox utilizes a content script to add HTML to a webpage when a button is clicked. The injected HTML includes an iFrame nested in multiple div elements. Below is the relevant part of the content script: var iFrame = document.create ...

Error encountered in Typescript: SyntaxError due to an unexpected token 'export' appearing

In my React project, I encountered the need to share models (Typescript interfaces in this case) across 3 separate Typescript projects. To address this, I decided to utilize bit.env and imported all my models to https://bit.dev/model/index/~code, which wor ...

Invoke Javascript through CSS selector

On my webpage, I have implemented a mousemove-mask feature that was inspired by an existing codepen. However, there is one significant issue that I can't seem to resolve on my own. Despite my attempts to fix it, I believe someone with more expertise c ...

The shadows in Three Js are functioning correctly, although there are a few shadow lines visible below my model

I am currently in the process of modifying a three.js scene, despite having little experience with javascript and three.js. After successfully adding a shadow to my GLTF model, I noticed some yellow and red lines beneath the model that I cannot identify or ...

Encountering an issue with Angular directive attributes

I am attempting to create an angular directive that will extract a substring from a passed-in attribute. Below is the code I have written: HTML: <body ng-controller="MainCtrl"> <div><substring message="This is a test."></substri ...

Using Vue to append elements that are not part of the loop

While looping over a table row, I realized that each of the table rows should be accompanied by another table row containing additional data from the loop. Unfortunately, I am struggling to insert <tr class="data-spacer"></tr> <tr& ...

Tips for handling data strings using axios

In my node.js project, I am following a manual and attempting to display data obtained from jsonplaceholder app.get('/posts', async (req, res) => { const response = await axios.get('https://jsonplaceholder.typicode.com/posts'); ...

A step-by-step guide to incorporating expandable and collapsible images within a div element using X

I have successfully created dynamic divs with some data that expand and collapse perfectly. Now I am looking to add expand and collapse images on these divs. I am relatively new to designing in xslt. <xsl:template match="category[key!='org.model.C ...

Generating Multilayered PDF files with JavaScript in NodeJS

After reviewing the documentation for PDFMake, PDFKit, and WPS: PostScript for the Web, I couldn't find any information beyond background layers. It seems like Optional Content Groups might be what I need, but I'm unsure how to handle them using ...

AJAX request lacks the 'access-control-allow-origin' header

I'm currently integrating a weather API into my app to display real-time weather information. Although I've used this API before, I am now attempting to fetch the data asynchronously using AJAX to avoid full page reloads. Below is the JavaScrip ...

Is there a way to verify the presence of a selector in Puppeteer?

How can I use Puppeteer to check if #idProductType exists and if not, assign producttype to ""? I have tried multiple solutions but none seem to work. const urls = [myurls, ...] const productsList = []; for (let i = 0; i < urls.length; i++) ...

How can I incorporate an error page into this Express application?

I'm currently working on an express application that simulates a basic version of Twitter. One feature I'm trying to implement is an error page. This way, if there are any issues with the routing, users will see a friendly message instead of a g ...

In a REST api, what is the appropriate response for a property that is missing a value?

Is it better for a property with no value assigned to be returned as null, or should the REST API skip such properties entirely? Let's consider a user object example with first_name and last_name. (In the below example, last_name is not necessarily a ...

Utilizing a fallback option for HTML5 video with a flash player and the ability to manipulate the

My dilemma involves an HTML5 video where I am utilizing jquery to interact with the player using the code snippet: video.currentTime += 1;. However, when Internet Explorer switches to Flash plugins, my JQ commands cease to function. How can I manage and co ...

.load() not triggering for images that are not in the cache - jquery

In Safari and Opera, the callback function of .load doesn't wait for uncached images to be fully loaded. With cached images, it works perfectly fine. The code may seem a little complicated, but I'll do my best to simplify it... So, here is my J ...

What is the best way to style radio boxes in HTML to resemble checkboxes and display X's when selected?

I'm looking to create a form with radio boxes that resemble checkboxes and display a glyphicon x when selected. I've experimented with various solutions such as: input[type="radio"] { -webkit-appearance: checkbox; /* Chrome, ...