How can angular DI be effectively implemented with libraries such as Modernizr, lodash, and jquery plugins to optimize performance and functionality?

As I delve into the world of Angular, I've noticed that it's not very common to wrap third-party scripts in an AngularJS provider for dependency injection. I'm still trying to figure out the best approach to leverage DI with jQuery plugins, lodash, modernizr, and more.

Take a look at this example I stumbled upon:

var App = angular.module('Toolbar', []);

    App.directive('toolbarTip', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                $(element).toolbar(scope.$eval(attrs.toolbarTip));
            }
        };
    });
    

Check out the demo here:

While this method seems to work perfectly fine, I wonder if creating a value, constant, or other provider for the toolbar tip jQuery plugin would be a better approach than injecting it directly into the directive. Similarly, should we consider wrapping jQuery (not jQlite) in a provider for injection?

When dealing with Modernizr:

angular.module('someApp', [])

    .provider('Modernizr', function () {
        this.$get = function () {
            return Modernizr || {};
        };
    })

    .factory('cgEvents', function(Modernizr) {
        return {
            buttonPressedEvent : function() {
                if ( Modernizr.touch ) {
                    return 'touchstart';
                } else {
                    return 'click';
                }
            }
        };
    })
    

And when using lodash:

angular.module('someApp', [])

    .factory('_', function() {
        return window._; // assuming lodash is already loaded on the page
    });

    .directive('cgFillViewPort', function (_) {
        return {
            restrict: 'A',
            link: function(scope, $elm) {

                var resizer = function() {
                    // code executed on resize...
                };

                $(window).resize(_.throttle(resizer, 100));
            }
        };
    })
    

Is this a valid way of implementing dependency injection? I'd appreciate any insights or feedback on this matter!

Answer №1

It seems like you're headed in the right direction. I've been following a similar path and it has worked well so far (although I plan to refactor my code to utilize requirejs as my application grows). It's important to note that using jquery in AngularJS can lead to memory leaks. Since AngularJS applications are single-page apps and jquery objects exist outside of the angular scope, they may not be properly destroyed when routes change. Make sure to remove any jquery references in directives when the $destroy event is triggered.

For more information on this issue, check out this link.

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

Encountered difficulties while attempting to use keyboard input and received a null value when attempting to retrieve a data-* attribute using Python and Selenium

Encountered an issue with keyboard interaction and finding a null value for the data-* attribute during automated login attempts on Gmail using Python and Selenium While attempting to automatically log in to Gmail using Python and Selenium, I successfully ...

Troubleshooting a Problem with AppCheck Firebase reCaptcha Configuration

Currently integrating Firebase with my Next.js project. I've been attempting to configure AppCheck reCaptcha following the documentation and some recommendations, but I encounter an issue when running yarn build The build process fails with the foll ...

Root functionality or Angular service

I am considering a restructuring of my code to enable sharing a dialog page among different controllers. Each controller should have the ability to open the same dialog. I am unsure whether to implement the dialog as a service or a directive in order to ma ...

Formik's handleSubmit function seems to be being overlooked and not executed as

I've encountered an issue while trying to validate a form before submission using formik and yup validation. The form is divided into two parts, where the first part needs to be validated before moving on to the second part. I set a state handleShow(t ...

Unable to access and process POST parameters sent via ajax in PHP

When passing two parameters in the send method to index.php, an error "Undefined index" is returned by PHP. echo $_POST['fname']; submit.addEventListener("click", function(e){ e.preventDefault(); var xhr = new XMLHttpRequest(); xhr. ...

Having trouble displaying an image in p5.js on Visual Studio Code

I can't seem to figure out how to load images in visual studio code for p5.js. Can someone help me understand the process of loading images in p5.js? I've set up a new project, but the images I try to load are not displaying correctly. How can I ...

The server returned a response that was void of any content

I have encountered an issue while trying to retrieve data from my server. The request works perfectly fine when tested with Postman, returning the expected data. However, upon implementing the request in my application, I receive an empty object with prope ...

Issue encountered during execution of AngularJS unit test in Karma-Jasmine

MainCtrl.js var app = angular.module('mailApp'); app.controller('MainCtrl', ['$scope','$http',function($scope,$http) { $scope.sortType = 'date'; // default sort type $scope.sortReverse = false; ...

How can I make the lines of my drawer thicker in Material UI?

Currently, I'm in the process of implementing a left-side navigation bar for a web application I'm developing. The main challenge I'm facing is customizing the styles as desired when using the Drawer component. Specifically, I'm aiming ...

What are the steps to incorporating an Image in a React Native application?

My Image is not showing up when I try to render it using image uri, and I'm not sure why. Here is the code snippet I'm using in a React Native project. import React from 'react'; import styled from 'styled-components/native'; ...

I'm having trouble viewing all the options in Select2 because it won't allow me to scroll

I am facing an issue with my select2 selectbox. It is fetching data from PHP and converting them into options for the selectbox. Strangely, I am unable to scroll down the list of options. Our front-end developer set up the select2 selectbox inside a modal, ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

Is there a way to automatically remove a document in MongoDB and Node.js once its expiration date has passed?

I'm working on an appointment booking app and I need to automatically delete booking details after the booked date has passed. How can I make this happen? I attempted to use node-scheduler for this task, but it wasn't successful. The app itself ...

Angular module malfunction

Striving to adhere to the best coding practices, I ventured into developing an Angular app and arrived at the following setup: The index.html file includes: <!DOCTYPE html> <html ng-app='hrsApp'> <head> <title>Hrs app& ...

The function call datatables rows().ids() does not return a defined value

I have implemented the ID attribute for rows in my datatable: 'createdRow': function (row, data, dataIndex) { $(row).attr('id', data.json.unid); } Now, I am trying to retrieve the IDs under a button click: action: function () { ...

"Encountered an unexpected token in Javascript - jsp error

Recently, I started working on a JSP application and encountered an issue with passing URL variables from a servlet to a JSP page using request.getattribute. When trying to pass the data to a JavaScript function, we received the following error: Uncaught ...

Error in Typescript index: iterating over properties of a typed object

My scenario involves an interface that extends multiple other interfaces from an external library: interface LabeledProps extends TextProps, ComponentProps { id: string; count: number; ... } In a different section of the codebase, there is an ...

When using create-react-app with JEST to run tests, TypeScript errors are not displayed

When I write incorrect TypeScript code in my project set up with create-react-app, running tests using npm test does not show any errors in the terminal. Is this normal behavior? It would be helpful to see these errors to avoid writing incorrect TypeScript ...

Generating various API calls and delivering them to a template (Express + Node.js + Facebook open graph)

I am currently developing a unique Express Node.js application that utilizes the extraordinary capabilities of this remarkable Facebook SDK. Allow me to present my existing route for the root: app.get('/', Facebook.loginRequired(), function (req ...

Following each AJAX request, the page initiates a reload

Each time I make an ajax call, my page reloads, and I've attempted the following actions: Changing the button type to button Using event.preventDefault() Also attempted event.stopPropagation(); Below is a snippet of my app.js: $(document).ready(( ...