Developing an AngularJS directive in place of a bulky jQuery function

I have a javascript function, mainly utilizing jquery, that I currently run when the page loads. My goal is to convert this into an angularjs directive, but I am facing difficulties in figuring out how to achieve it.

As someone new to angular, any assistance would be immensely appreciated.

The only variable that remains unknown is PDFWIDTH, which will be stored in a $scope.pdf_width variable upon template load.

JQUERY FUNCTION

function zoomProject() { 

    var maxWidth = $("#formBox").width(), percent = maxWidth / PDFWIDTH;

    $("#formScale").css({
        'transform': 'scale(' + percent + ')',
        '-moz-transform': 'scale(' + percent + ')',
        '-webkit-transform': 'scale(' + percent + ')',
        '-ms-transform': 'scale(' + percent + ')'
    });
    $(".trimSpace").css('width', (PDFWIDTH * percent) + 'px');
    $("#formBox, .trimSpace").css('height', ($("#formScale").height() * percent) + 'px');

}

HTML

<div id="formBox">
    <div class="trimSpace">
        <div id="formScale"></div>
    </div>
</div>

Currently, I have laid the foundation for resizing an element to fit the entire window width and height. I am exploring the most suitable approach to accomplish this task.

What are your thoughts? Should I simply replicate the jquery functionality above and integrate it similarly to the directive below? Or do you believe there exists a better way in terms of leveraging javascript/angular?

.directive('zoom', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        scope.getWindowDimensions = function () { return { 'h': w.height(), 'w': w.width() }; };
        scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
            scope.windowHeight = newValue.h;
            scope.windowWidth = newValue.w;
            scope.style = function (amount) { return {  'height': (newValue.h - amount) + 'px', 'width': (newValue.w - amount) + 'px' }; };
        }, true);
        w.bind('resize', function () { scope.$apply(); });
    }
})

Answer №1

Just solved my own query. Open to any suggestions or recommendations.

In case anyone is curious, here is the solution:

JS

.directive('zoom', function ($window) {
        return function (scope, element) {
            var w = angular.element($window);
            scope.getWindowDimensions = function () { return { 'h': w.height(), 'w': w.width() }; };
            scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
                scope.windowHeight = newValue.h;
                scope.windowWidth = newValue.w;
                var formBox = angular.element($("#formBox")), formScale = angular.element($("#formScale"));
                scope.formScale = function(pdfwidth) { 
                    var percent = formBox.width() / pdfwidth;
                    return { 'width': pdfwidth+'px', 'transform': 'scale(' + percent + ')', '-moz-transform': 'scale(' + percent + ')', '-webkit-transform': 'scale(' + percent + ')', '-ms-transform': 'scale(' + percent + ')' } 
                };

                scope.trimSpace = function(pdfwidth) {
                    var percent = formBox.width() / pdfwidth;
                    return { 'width': (pdfwidth * percent)+'px', 'height': (formScale.height() * percent)+'px'  } 
                };

                scope.formBox = function(pdfwidth) {
                    var percent = formBox.width() / pdfwidth;
                    return { 'height': (formScale.height() * percent)+'px'  } 
                }

            }, true);
            w.bind('resize', function () { scope.$apply(); });
        }
    })

HTML

<div id="formBox" ng-style="formBox(pdf_width)" zoom>
    <div class="trimSpace" ng-style="trimSpace(pdf_width)" zoom>
        <div id="formScale" ng-style="formScale(pdf_width)" zoom></div>
    </div>
</div>

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

How can we stop every tab pane in (bootstrap five) from sharing the same scroll position? Each tab is currently synchronized with the scroll position of the others

In Bootstrap 5, the scroll position remains the same when switching between tabs in the tab pane. Whether moving from tab #1 to tab #2, both tabs are at the identical scroll position, failing to preserve each tab's specific location. <div class=&qu ...

Please refrain from refreshing the page multiple times in order to receive updated data from the database

Currently, I have created a countdown timer from 00:60 to 00:00. However, once the timer reaches 00:00, I am looking to refresh the page only once in order to retrieve a new value from the database. Does anyone have any suggestions on how to achieve this ...

Troubleshooting: Angular Custom Elements malfunction on Firefox, Microsoft Edge, and Internet Explorer

Experimented with the Angular Elements Demo After downloading, installing, and building the demo locally. Implemented the following code: <!doctype html> <html lang="en> <head> <meta charset="utf-8> <title>Angular Eleme ...

Issue with bootstrap collapsible panel when used within ng-if directive is causing it to malfunction

When using a bootstrap collapsible panel with angular js and placing it inside a div while adding the ng-if, I encountered issues with the collapsible not working properly. User <input type="checkbox" ng-model="isUser"/> <div class="col-md-12" n ...

Trigger a jQuery event when a value is changed

Greetings everyone, I am currently seeking a method to trigger an event each time the values change. Within a div element, there is a live clock that is constantly running: <span id="LiveClockIE">The current time is: 9:37:24 AM</span> I am l ...

Using the return statement to set a value from a callback function in TypeScript

As I retrieve data from an array of class People, each person has an attendance list represented by Observable<any[]>. // Defining the Person class class Person { id: number; name: string; attendance: Observable<any[]>; // Represents ...

knockout, loop within a loop

Imagine I have a group of Humans who own Cats, and those Cats have Kittens class Person { String name; Cat[] cats; } class Cat { String name; Kitten[] kittens; } class Kitten { String name; } Now I want to display all my Kittens with ...

Obtained a ZIP file via CodeSandbox that contains a Vue.JS webpage. However, the index.html file yielded an

I have created my first ever Vue.JS / Vue2Leaflet app. It runs perfectly fine on codesandbox.io. However, when I download the ZIP file and try to open the index.html file, it appears blank. Is there something specific that needs to be done to make it work, ...

Having trouble launching an AngularJS website within a Docker container

I am currently working on running my angular site within a docker container using boot2docker. The structure of the Dockerfile is as follows: FROM ubuntu:14.04 RUN sudo apt-get update RUN sudo apt-get install -y npm # Setting the directory for commands ...

Achieving vertical alignment of form controls with labels that wrap in a row using Bootstrap 4

I am facing an issue where input elements in a row with labels above them are causing alignment problems when the screen width is reduced. The longer labels wrap to the next line and push the input element down, increasing the overall height of the row: h ...

Update the text using JavaScript to modify the price range dropdown when the user clicks away

Dropdown functionality is working when selecting a price, but updating the price in the text box manually does not trigger an update. How can you implement an onblur change event for manual entry of prices? JSFiddle function nFormatter(num, digits) { ...

"Transcribe as HTML" for embedded IFrame components within Chrome's Inspector tool

When using Chrome's web inspector, there is a helpful "Copy as HTML" option when you right-click on a DOM element. However, it seems that this feature does not include the contents of IFrame tags, even though they are displayed in the inspector as chi ...

Issue: A file that has been uploaded completely ignores the req.on() method in NodeJS

I am currently using MEAN.IO to create a web application. Right now, I am working on implementing an image uploader feature. I have decided to use angular-file-upload for this purpose, and it seems to be functioning well. However, I am facing an issue on ...

Transform charset X to Unicode using Java

What is the process to convert a specific charset to unicode in Java? We have discussed charsets extensively, but this particular topic has not been covered yet. I have a hex string that follows the criteria length%4==0 (e.g. \ud3faef8e). Typically, ...

We apologize, but the requested resource through HttpGet could not be located

I am attempting to retrieve data from a website, starting with testing on localhost. Unfortunately, the Get request is not successful. However, switching it to POST resolves the issue. Error: The requested resource could not be found. Controller Action: ...

Incorrect Request Method for WCF json POST Request Leads to 405 Error (Method Not Allowed)

Hey there, I'm facing an issue with using Microsoft Visual Studio to create a WCF web service. Everything runs smoothly within Visual Studio, but when I try to connect to the service from outside, it fails to establish a connection. At first, I encoun ...

NPM TypeORM is throwing the error message "Duplicate migrations" when changes are made to a migration file

Recently, I made a modification to an existing table by adding a new column using the command npm run migration:generate <filename>. Unfortunately, I realized later on that I had misspelled the column name and needed to correct it (showComission -&g ...

Animating a progress bar with JQuery

Having issues with displaying a progress bar using jquery and javascript, as it is not appearing on the page. var show_time = Math.floor(Math.random() * 10000) + 5000; setTimeout(function() { $("#progress").hide() }, show_time); var myCountdown = $( ...

The functionality of Angular animate becomes compromised when there is a conflict between predefined CSS states and transition states

Explore this example CSS code: /* animations at the start */ .error-animation.ng-enter { -webkit-transition: 0.5s linear all; transition: 0.5s linear all; opacity: 0; } ...

Learn how to easily upload multiple files from various upload points onto a single page using Node.js and express-fileupload

After searching on various platforms, including StackOverflow, I couldn't find a solution that fits my specific scenario. I've been struggling for hours to resolve this issue... In my handlebars page, there is an option for the user to upload fi ...