Adjust the class attribute in real-time

My image doesn't appear in the correct position when I dynamically set it using the margin-top.

Below is an image with a red arrow pointing to the right, which is what I want:

https://i.stack.imgur.com/ue4mY.png

The CSS I have is as follows:

.file_arrow_right {
        background: url('../images/right_icon.png') no-repeat;
        cursor: pointer;
        width: 35px;
        height: 22px;
        background-size: 18px;
        background-position: 0px;
        margin-top: -500px;
    }

I only want to change the margin-top of the above CSS dynamically based on certain image height, so I used the following code:

app.controller('filePreviewSectionCtrl', 
function ($scope, $q, $sce, $rootScope, $filter, $compile, $timeout, $state, 
$modalInstance, commFile, blobUrl) {    
    var myBase64 = "data:"+commFile.fileType+";base64,"+commFile.image+"";
    //jpeg, .jpg, .bmp, .png, .txt
    if(commFile.fileType.split("/")[1] == "jpeg" || 
     commFile.fileType.split("/")[1] == "jpg" ||  
     commFile.fileType.split("/")[1] == "bmp" || 
     commFile.fileType.split("/")[1] == "png") {
        $scope.imgBlob = myBase64;

        var img = new Image();
        img.src = myBase64;
        img.addEventListener('load',function(){
            var width=img.width;
            var height=img.height;
            console.log("width: "+width);
            console.log("height: "+height);
            // should change dynamically
            $scope.arrowMarginTop = "margin-top: "+height/2+"px";
        });     
    } 
})

This is the HTML:

       <script type="text/ng-template" id="filePreviewSectionCtrl.html">
        <div id="dynamicFile" style="width:100%; height:100%;">
            <div class= "file_arrow_right" ng-class="arrowMarginTop">
            </div>     
        </div>          
       </script>

UPDATE:

Following @Temani's suggestion that span elements are inline and won't be affected by margin-top, I changed the span to a div. Then, I used @Satpal's answer to dynamically change the CSS.

Answer №1

If you are defining the CSS rule within the scope variable arrowMarginTop, it is important to utilize the ngStyle directive rather than ngClass

<span class= "file_arrow_right" ng-style="arrowMarginTop">
        </span> 

Make sure to structure it as an object like this:

$scope.arrowMarginTop = { "margin-top" : height/2 + "px" };

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

Error: The Angular-Summernote editor is unable to upload images, as the object

I'm having difficulty understanding how to utilize the angular-summernote callback on-image-upload. Here's the code in my view: <summernote data-editable="editable" data-on-image-upload="imageUpload(files, editor)"></summernote> My ...

The ng-repeat directive adds an additional line after each iteration of the list item

Whenever the angular directive ng-repeat is utilized with an <li> element, I notice an additional line appearing after each <li>. To demonstrate this issue, see the simple example below along with corresponding images. Here is a basic example ...

Show the URL hash as url.com/something#/ rather than url.com/something/#/

I'm encountering a peculiar issue with my Angular v1.6.5 setup. My routes seem to be acting strangely, for example: $routeProvider .when('/', { templateUrl: 'myTemplate', controller: 'myController', method: &apo ...

Use AngularJs service injected in run closure for testing purposes

Testing an angularjs service called MyService has been a bit challenging. It seems like Angular tries to use the service before it is fully loaded when I try to inject it directly. However, if I mock MyService using $provide, it does work but then I don&ap ...

Purge precise LocalStorage data in HTML/JavaScript

How can a specific item in the localStorage be cleared using javascript within an html file? localStorage.setItem("one"); localStorage.setItem("two"); //What is the method to clear only "one" ...

Optimal practices for localization

Looking to translate our site into multiple languages starting with one language but planning for more in the future. Considering the most effective way to accomplish this. The plan is to use subdirectories to organize the html files, with shared files su ...

Asynchronous JavaScript function within a loop fails to refresh the document object model (DOM) despite

I have been working on a function that utilizes ajax to retrieve instructions from a backend server while the page is loading. The ajax code I've written retrieves the instructions based on the number provided and displays them using the response.setT ...

Adjust the color of the active link on the page using Angular and CSS

I have a project that I need to modify by adding a sub menu that appears on every page but is only coded once. My goal is to highlight the link for the current page, all within one HTML snippet. Although the list renders correctly, I'm struggling to g ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

Navigating through pages in an Angular single page application with ASP.Net MVC Web API

Users are presented with a selection of different companies Once a user chooses a company, they are then shown a list of reports specific to that company I have set up my Angular application in the following manner: angular.module('xcmApp', [&a ...

Adding custom fonts to DOMPDF: a step-by-step guide

First, I moved the dompdf library folder to /dompdf Next, I added a /fonts folder containing Roboto-Black.ttf Then, I created an index.php file <?php // Autoloader inclusion require_once 'dompdf/autoload.inc.php'; // Namespace reference ...

Utilizing Selenium to automatically scroll through a Flickr page in order to capture and retrieve all the

Hey there! I'm currently working on a project to retrieve Flickr public images from a specific group. So far, I've been able to successfully parse the HTML and extract the image hrefs. However, I'm facing a challenge when it comes to retriev ...

How can you confirm the validity of a dropdown menu using JavaScript?

<FORM NAME="form1" METHOD="POST" ACTION="survey.php"> <P>q1: How would you rate the performance of John Doe? <P> <INPUT TYPE='Radio' Name='q1' value='1' id='q1'>1 ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

Troublesome Suckerfish CSS Navigation Menus failing to function properly on IE7

Feeling completely exasperated, I am encountering issues with aligning the drop downs under the parent item in IE7. Despite functioning properly in all other browsers, including IE8, the drop down menu is not lining up correctly in IE7. In IE7, the drop d ...

Attempted to simultaneously initialize angular multiple times using express 4

Every time I attempt to load an Angular route and template, I encounter the following error message: WARNING: Attempting to load angular multiple times. I suspect there is a routing issue leading to an infinite loop but pinpointing the source of the prob ...

Implementing dynamic styles for a checked mat-button-toggle in Angular 6

How can I customize my button-toggle when it is checked? The current code I have doesn't seem to be working... This is the code snippet: <mat-button-toggle-group #mytoggle (change)="selectoption($event)" value="{{num}}"> <mat-bu ...

Boosting your website with a slick Bootstrap 4 responsive menu that easily accommodates additional

I have incorporated a main menu in my website using the Bootstrap 4 navbar. However, I also have an additional div (.social-navbar) containing some extra menu items that I want to RELOCATE and INSERT into the Bootstrap menu only on mobile devices. Essentia ...

What is the best way to implement the concept of setting a minimum size for a scrollable element based on its content and a

In the interest of simplicity, let's assume that my fixed height is 100px. So, the CSS expression for the question in the title would be: height: min(min-content, 100px); This means to take the minimum value between content height and 100px. Unfortun ...

Tips for positioning the navbar to avoid covering the logo:

I am experiencing difficulty in aligning my navbar. When I resize the window, the navbar overlaps with the logo... Here is the Fiddle Here is the code: <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" style="background: rgba(0,0, ...