Incorporating styling preferences within a directive's template

One of the directives I am currently working on looks like this:

app.directive('MessageChild', function($timeout) {
    return {
        restrict: 'E',
        scope: {
            pos: '=?',
            msg: '='
        },
        link: function(scope, element, attr) {
            scope.msg = attr.msg;
            scope.styleVar = "100"  //I would like to incorporate this variable
        },
        template: '<style> div {position: absolute; top: **<scope variable or binding here>** }</style>' +
'<div>{{msg}}</div>'
})

This is merely a simplified illustration of my issue. In reality, my styles are much more complex and include animations. After some operations, I need to pass the resulting value to my styles. However, Angular does not allow me to insert bindings within styles. Can anyone advise me on how to insert a variable at this specific location from inside my directive?

Answer â„–1

One suggestion is to create an object within the link function and then pass it into an ngStyle directive.

app.directive('messageChild', function($timeout) {
    return {
        restrict: 'E',
        scope: {
            pos: '=?',
            msg: '='
        },
        link: function(scope, element, attr) {
            scope.msg = attr.msg;
            scope.styleVar = {
              'color': 'blue',
              'position': 'absolute',
              'top': '100'
            };
        },
        template: '<div ng-style="styleVar">{{msg}}</div>'
    };

});

Example Plunker:

http://plnkr.co/edit/b1uO8N

EDIT

If you prefer, you can achieve the same result using the <style> tag:

app.directive('messageChild', function($timeout) {
    return {
        restrict: 'E',
        scope: {
            pos: '=?',
            msg: '='
        },
        link: function(scope, element, attr) {
            scope.msg = attr.msg;
            scope.styleVar = 'blue';
        },
        template: '<style> div {position: absolute; top: 100; color: {{styleVar}}}</style><div>{{msg}}</div>'
    };

});

Example Plunker:

http://plnkr.co/edit/8NxKFS?p=preview

Answer â„–2

Andrew Sala's response seems to be on point, so I decided to experiment with the plunker to explore its potential for animation.

<!DOCTYPE html>
<html ng-app="plunker">

<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');   </script>
<link rel="stylesheet" href="style.css" />
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13727d74667f72613d79c7f">[email protected]</a>" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
<script src="app.js"></script>

<style>
  * { transition: all 0.5s}
</style>
<script>

var app = angular.module('plunker', []);

app.controller('MainCtrl',['$scope','$timeout', function($scope, $timeout) {

var mc = this;

mc.name = 'World';
mc.msg = '!';

mc.data = { pos: 250, color: 'blue', size: 100 }; 

 $timeout(function() {
   mc.msg = "bob";
   mc.data = { pos: 240, color: 'yellow', size: 160  }; 
 }, 1500);

 $timeout(function() {
   mc.msg = "bob is";
   mc.data = { pos: 230, color: 'orange', size: 210 }; 
 }, 2500);

 $timeout(function() {
   mc.msg = "bob is COMING!";
   mc.data = { pos: 220, color: 'red' , size: 300}; 
 }, 3500);

 }]);

 app.directive('messageChild', function($timeout) {
   return {
     restrict: 'E',
     scope: {

        stuff: '=',
        msg: '@'
     },
     link: function(scope, element, attr) {
      console.log(scope.stuff);

        scope.styleVar = scope.stuff.color;
          scope.pos = scope.stuff.pos;

        scope.$watch('stuff', function() {
          console.log(scope.stuff);
          scope.pos = scope.stuff.pos;
          scope.styleVar = scope.stuff.color;
          scope.size = scope.stuff.size;
        })
     },
     template: '<style> div {position: absolute; top: {{pos}}px; left: 100px; font-size: {{size}}% ; color: {{styleVar}}}</style><div>{{msg}}</div>'
    };

 });
</script>

</head>

<body ng-controller="MainCtrl as mc">
  <p>Hello {{mc.name}}!</p>
  <message-child msg="{{mc.msg}}" stuff="mc.data" >stuff</message-child>
</body>

</html>

Check out the Animated Text here

You have the option to include a style tag for each item individually or utilize ng-style. I've applied different classes for my animations, along with some inline styling for effects like glows and blurring.

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

The isOpen State in AngularJS Accordion Component

Is it possible to determine if an accordion-group is open or closed without using the isOpen directive? I am curious if there is a way to access this information solely through HTML. I have experimented with two-way binding to store the state, but this app ...

Looking for a way to keep the mobile ad unit fixed at the bottom of the screen

I am currently working on incorporating a 320x50 mobile ad into the mobile version of my website. The goal is to have the ad fill the entire width of a mobile device. However, the issue I'm facing is that the ad appears small and does not stretch acro ...

Click to Rotate Angular Chevron

Is it possible to animate the rotation of a chevron icon from left-facing to right-facing using Angular? CSS: .rotate-chevron { transition: .1s linear; } HTML: <button [class.button-open]="!slideOpen" [class.button-close]="slideOpe ...

Clickable element to change the display length of various lists

I am working on a project where I have lists of checkboxes as filters. Some of these lists are quite long, so I want to be able to toggle them to either a specified length or the full length for better user experience. I have implemented a solution, but th ...

Code snippets to reduce excess white space on a website using HTML and CSS

On my website, there are multiple tabs, each containing content from an HTML file. When a user clicks on Tab1, boxes with images are displayed. The layout can be seen in the following Code Demo: Code Demo here There seems to be extra space before and afte ...

Creating a persistent footer in a modal: A step-by-step guide

I'm currently working on a react-modal that slides in from the bottom of the screen with an animated effect. The challenge I am facing is getting the footer of the modal to stay fixed at the bottom of the browser window. Despite using the standard CSS ...

Using CSS to align and place elements

Currently facing a challenge with my HTML/CSS code regarding the horizontal centering of two divs (A, B) within one absolutely positioned div (C) that contains background images. Key aspects to consider: The bottom edge of the larger div (A) should alig ...

AngularJS - FormController inaccessible to dynamic forms

It is important to consider that one customer may have multiple contact information. To create a user-friendly HTML form, I have utilized a structure similar to the following: <div> <customer-form/> <!-- single <form> element ...

What is the process for adjusting positioning in bootstrap?

After spending countless hours attempting to create a responsive webpage using the bootstrap grid system, I have hit a dead end. Here is the code I have been working with: <div class="row"> <div class="col-md-2" align=&quo ...

Creating vibrant row displays in Vue.js: A guide to styling each row uniquely

I am not a front-end developer, so Vue and JS are new concepts for me. Currently, I am working on an application for managing sales. One of the components in my project involves displaying invoices in a list format. To make the rows visually appealing, I ...

Choosing descendant elements in CSS styling

Is there a way to select child elements in sequence? For instance: <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li> ...

How do you prevent items from shrinking in a flex container when they have more content?

I am facing an issue with a flex container where the items are set in a row. Once it reaches the end of the viewport width, I want it to overflow-x: scroll. However, instead of enabling scrolling, all items shrink when more items are added to fit the scree ...

Unable to choose the specific div element within the container that has an inset shadow applied by utilizing Pseudo

It seems that I am encountering an issue when trying to select the div elements within a container that has a defined shadow using pseudo elements ::before OR ::after. Once the shadow is applied, the div elements become unselectable. Please refer to the c ...

The scope of the UI Bootstrap directive does not seem to be getting refreshed

Currently working on a project that involves AngularJs, I am seeking assistance in creating a dialog box where users can input a string. The goal is to display this string later on the page prominently. To achieve this, I opted for the modal directive fr ...

What is the best way to conceal Bootstrap accordion content when first loading my single-page application?

I am currently developing a single page application for an ESP32 device. I have chosen to keep all the content in one document as there is not a lot of information to display. My approach started with using the collapse class from Bootstrap 4.1.2. While i ...

Showing the Datepicker from jQuery right in the middle of the screen

Here's the generated code as default: <div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper- clearfix ui-corner-all ui-datepicker-multi ui-datepicker-multi-2" style="width: 34em; position: absolute; left: ...

Implement dynamic changes to uib-tooltip-html content

Is it possible to combine content on a uib-tooltip-html like shown in the following example? app.controller("testController", function($scope, $http, $interval, $sce) { $scope.text = $sce.trustAsHtml('<div>Some text</div>'); ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'ÅšlÄ…sk' even though it's not listed. For example: I select 'test' but it shows as 'ÅšlÄ ...

What is the reason behind shadow dom concealing HTML elements when viewed in inspect mode?

https://i.stack.imgur.com/UZM7f.png Monday.com has implemented Shadow Dom to protect its source code. How can I work around this limitation? ...

Incorrect color change on button triggered by onMouse actions and state fluctuations

While creating a user profile on my app, I encountered an issue with button coloring. When I try to add color functionality to the button, it turns red instead of green and remains red even when the mouse is not hovering over it. My goal is to have the but ...