Improving TypeScript functionality in AngularJS 1.5.7 directive - ...issues with passing arguments and encapsulating 2 classes

I am currently working on an older project that was built with AngularJS 1.5.7 and I want to incorporate TypeScript for new additions. This means only the newly added features will be in TypeScript, without a complete migration at this point.

Through my research, I have figured out how to create a directive using TypeScript in AngularJS.

import * as angular from 'angular';

angular
    .module('starter.directives')
    .directive('lateralScrollbar', ['$timeout', ($timeout) =>
        new (class {
            restrict = 'A';

            constructor(
                private $timeout
            ) { }

            link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) {
                let directive = this;

                new (class {
                    constructor(
                        scope: ng.IScope,
                        element: ng.IAugmentedJQuery,
                        attrs: ng.IAttributes
                    ) {
                        scope.something = 'Loading';
                        /** 1. How to optimize that "directive" is not needed here? Maybe that I can use "this" instead or "parent" */
                        directive.$timeout(() => scope.something = 'OK', 1000);
                    }
                })(scope, element, attrs);
            }
            /** 2. How to optimize so that I can pass the arguments with which the function was called. For example fn.apply(); and ...args? */
        })($timeout)
    ]);

There are two comments within this code snippet.

  1. How can I optimize so that "directive" is not required here? Perhaps I could utilize "this" instead of "parent".
  2. How can I optimize to pass the arguments used when calling the function? For instance, fn.apply(); and ...args?

The first comment raises an interesting point. Currently, I call the directive normally with an array of dependencies and include the function at the end. However, this process seems unnecessarily complex. The function creates an object of the class within it, which then has a link function that defines the directive as this, allowing me to access the passed arguments (e.g., $timeout).

Additionally, I notice that I define the $timeout variable four times. Once in the Angular directive's dependencies, once in the class constructor, once as an argument for initial class initialization, and finally in the function which wraps the first class.

This experiment failed because it couldn't handle the ...args concept. I'm unsure how to further optimize this.

import * as angular from 'angular';

angular
    .module('starter.directives')
    .directive('lateralScrollbar', ['$timeout', (...args) =>
        new (class {
            restrict = 'A';

            constructor(
                private $timeout
            ) { }

            link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) {
                let directive = this;

                new (class {
                    constructor(
                        scope: ng.IScope,
                        element: ng.IAugmentedJQuery,
                        attrs: ng.IAttributes
                    ) {
                        scope.something = 'Loading';
                        /** 1. How to optimize that "directive" is not needed here? Maybe that I can use "this" instead or "parent" */
                        directive.$timeout(() => scope.something = 'OK', 1000);
                    }
                })(scope, element, attrs);
            }
            /** 2. How to optimize that I can pass the arguments with that the function was called. For example fn.apply(); and ...args? */
        })(args)
    ]);

Error: TS2554: Expected 1 arguments, but got 0.

If anyone can offer assistance, I would greatly appreciate it! Thank you in advance!

Answer №1

To utilize TypeScript, the initial step involves creating a directive using a class and then designating that class as an Angular application directive via the factory method.

For a more comprehensive understanding, refer to the links provided below.

Link 1 Link 2

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 function FileSaver.js saves a file as Xlsx format

I have been using filesaver.js to successfully export my div (which contains multiple tables) to Excel as XLS with the following code snippet. var blob = new Blob([document.getElementById('exportable').innerHTML], { type: "application/vnd.op ...

What is the process for transferring an existing collection or data in Firestore to a subcollection?

My firestore database currently has the following structure with documents: root | |---transactions/... I am looking to transfer all transactions to a new subcollection as shown below: root | |---users/user/transactions/... Any suggestions on how I can a ...

What are the best methods for querying and updating a self-relation in Prisma?

I recently obtained some self-relation tables directly from a specific Prisma example. model User { id Int @id @default(autoincrement()) name String? followedBy Follows[] @relation("follower") following Follows[] @rel ...

Is there a way to stop jQuery dragging functionality from causing the page to scroll unnecessarily

Whenever I drag an element from div1 to div2, the scrollbar in div1 keeps extending until I drop the element in div2. How can I prevent this extension without breaking the element being dragged? <div class="container-fluid"> <div class="row"> ...

Issues arise with element binding when incorporating AngularJS UI-Router

My website utilizes AngularJS and UI-Router. To create a separate login page that is not injected into the main view, I decided to divide the index.html file into two parts: one with layout and script includes, and another with just script includes. This w ...

What is the most effective way to retrieve the value of a child component in Angular 2 and pass it to the parent component?

I am working on a project with a child component (calendar) and a parent component (form). I need to select a value in the calendar and then access that value in the form component. What is the best way to achieve this? Child Component.ts: import { ...

Avoid using `object` as a data type, as it can be challenging to work with

const useSetState = <T extends dataStructure>( initialState: T = {} as T ): [T, (patch: Partial<T> | ((prevState: T) => Partial<T>)) => void] => { const [state, setState] = useState<T>(initialState); const setMergeSta ...

Convert this text into HTML code: "Textarea to

I have a basic <textarea> element that I want to transform links (www.google.com, msn.com, etc) and line breaks (\r\n) into HTML code. I found one library for converting links into <a hrefs>. Another library can convert line breaks i ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

How can I cancel a JavaScript timer set from a different function?

Can anyone help me with stopping the timer initiated by setInterval() in JavaScript? I need to be able to stop this timer through another function. Is it possible to kill all timers on the page using jQuery or JS? Below is the function where I started the ...

TypeScript Interfaces: A Guide to Defining and

In my angular2 application, I have created interfaces for various components. One of these interfaces is specifically for products that are fetched from a remote API. Here is the interface: export interface Product { id: number; name: string; } ...

What is the proper way to format parameters being sent to the server using JavaScript on the back end

Struggling to make the following code work in my ASP.NET demo application, looking for some guidance here. Check out the javascript code below: function checkUserName() { var request = createRequest(); if (request == null) { alert("Unable ...

Uninterrupted jQuery AJAX calls

I have a scenario where I need to periodically update an image on my view using ajax every 10 seconds. Any suggestions on how I can achieve this? Appreciate the help. ...

Running a PHP script within an HTML file without the need to refresh the page

I need to execute a PHP File that was embedded in a div within my HTML code. The main page consists of a form and a table. The form adds rows to the MySQL table, while the table dynamically displays the content of the MySQL table. I am trying to find a way ...

What are the steps to implement zone.js in your Angular application?

I am looking to utilize zone.js in my Angular project beyond just the runOutsideAngularZone function. My attempt to include it looked like this: import { zone } from 'zone.js'; Unfortunately, I encountered this error: error TS2306: File &apos ...

Dividing a string into an array and displaying it in a table using Laravel

Retrieving a string from the database and using the explode function to split the values. Below is the code snippet: $data = DoctorRegistration::select('products') ->where('doctorid','=',$doctorid) ->get(); ...

How can I only replace every second occurrence in a JS string?

Looking for help with JavaScript: "a a a a".replace(/(^|\s)a(\s|$)/g, '$1') I thought the result would be '', but it's showing 'a a' instead. Can someone explain what I'm missing? To clarify, I want to r ...

Is it possible to organize and filter a dropdown menu in JQuery based on a secondary value (new attribute)?

Can the drop-down list be sorted by value2? <select id="ddlList"> <option value="3" value2="3">Three</option> <option value="1" value2="1">One</option> <option value="Order_0" value2="0">Zero</option> </sele ...

Tips for successfully transferring values or parameters within the Bootstrap modal

How can I create a cancel button that triggers a modal asking "Are you sure you want to cancel the task?" and calls a function to make an API call when the user clicks "Ok"? The challenge is each user has a unique ID that needs to be passed to the API for ...

Ways to enhance the performance of my websites' backend systems

Greetings! I am currently working on developing backends in ASP.NET 2.0, and have taken steps to optimize the performance by caching images, GZIPing CSS and JS files. The load speed of each option is good, but I am eager for even faster loading times. Alt ...