Incorporate an external object not native to the Angular framework within a factory

We're in the midst of a debate and I'm hoping you can help us reach an agreement.

Imagine I have a basic factory set up like this:

angular.module('myModule', [])

.factory('Fact', function() {
    var Fact = function() {
        var that = {};

        that.var1 = [];
        that.var2 = [];

        return that;
    };

    var fact = {
        get: function() {
            return Fact();
        }
    };

    return fact;
});

I discovered that if I rearrange the code this way, it still works:

angular.module('myModule', [])

.factory('Fact', function() {
    var fact = {
        get: function() {
            return Fact();
        }
    };

    return fact;
});


var Fact = function() {
    var that = {};

    that.var1 = [];
    that.var2 = [];

    return that;
};

Essentially, I could separate the Fact object's code and place it in another plain .js file, include it before the Angular code (in the index.html file) and it would still function properly.

However, we are debating whether or not this is a good practice because having Fact on the global scope may not be ideal in terms of best practices.

In what scenarios do you think this solution is or isn't advisable?

Is there a way to incorporate "non-Angular" code (simple JavaScript code written in a separate .js file) into an Angular factory?

Answer №1

When it comes to managing factories, services, providers, constants, and values in Angular, it's best to keep all code within Angular's constructs unless dealing with third party code.

If you are incorporating third party code, you may not have control over how it registers itself. It could use the global scope or provide a module export option.

The most efficient and secure way to integrate third-party code into Angular is by utilizing a build-step using a module bundler.

For example, if you want to utilize a package like "foojs" within Angular using browserify:

Firstly, install the package via npm

npm install --save foojs

Then implement it as shown below:

var foojs = require('foojs');

var app = angular.app('myapp')

app.service('myservice', function() {
  // safely use foojs here
});

Similar results can be achieved with WebPack as well.

This approach is more secure because, after the build step, all modules will be encapsulated within a function that safeguards the global scope.

If using a module bundler is not possible, resorting to the global scope and allowing the third party code to bind onto the window object is the only alternative.

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

React input field keeps losing focus during re-render operations

My current project involves using React to create an input text that displays a value from an in-memory data store and updates the store when the input value changes, triggering a re-render. However, I am facing an issue where the input text loses focus du ...

How can I determine the appropriate time to hide the loading screen after the model has been loaded with gltfLoader and before the scene is rendered?

I am currently working on a project using threejs version 106, where I have integrated both the webGLRenderer and CSS2DRenderer. My main challenge lies in loading a glb model and displaying a loading progress bar utilizing the onProgress callback of the l ...

What is the best way to connect a string to a scoped variable in a view?

I'm looking to connect a string to a scope variable that will be determined by user input in an input field located within a specific view. The goal is for the combined string and scope variable value to appear in another div within the view. Here&ap ...

Jest fails to pass when encountering the double colon

Having issues testing a React app using Jest. I encounter errors when running my code: FAIL src\App.test.js ● Test suite failed to run C:/Users/user1/Projects/map-editor/src/App.js: Unexpected token (40:33) 38 | <div cla ...

Leveraging onClick in combination with React's AutoBind

Just started learning React, so please point me towards documentation if I missed anything. I'm attempting to initiate an Ajax call using the onClick method following a tutorial on React. See the code snippet below. doSomething: function() { // ...

Having issues with implementing PrimeNG components (Directive annotation not detected)

Having difficulty integrating PrimeNG components (beta5) with Angular2 (rc.1). Whenever attempting to utilize a component, such as the menubar, the following error is consistently encountered: No Directive annotation found on Menubar New to Angular and ...

Adjusting the alignment of a facial image on Canvas by selecting specific click-points

I have a unique idea for an app that allows users to correct a tilted face with just 2 clicks The concept is simple - users click on the middle of the nose and the middle of the eyebrows within the image to generate two points: eyebrowMiddle(x1,y1) and no ...

What is the process to retrieve the username from my system and display it in a web browser?

Seeking assistance to retrieve my system's username and display it on a web browser. Currently, I have been using ActiveXObject method, which successfully retrieves the username, but has drawbacks such as requiring ActiveX to be enabled and only works ...

Facing issues with the template URL not functioning properly during the migration from Angular 1.5 to Angular 6

I am currently in the process of migrating an Angular 1.5 project to Angular 6, but I've encountered an issue with the templateUrl not working in the Angular 1.5 component. The packages I am using are: Angular CLI 6.0.8 TypeScript 2.7.2 Angular 6.0.7 ...

Slider Adjusts Properly on Chrome, but Not on Firefox

Visit this URL This link will take you to the QA version of a homepage I've been developing. While testing, I noticed that the slider on the page works perfectly in Chrome and IE, but has layout issues in Firefox where it gets cutoff and moved to th ...

Unable to produce scrolling animation using JavaScript

I'm trying to implement a feature on my website where the page scrolls with a sliding effect when the user presses the "Scroll" button. However, I've encountered issues as it doesn't seem to work despite adding the necessary tags to my HTML ...

Enter path on angular-ui-router

I've been experimenting with this demo of the angular-ui-router by using a WordPress site to host the javascript file. The angular app has a route called /login. Clicking the link on the homepage correctly loads the login template, but directly typing ...

Vanishing elements when employing the react-router library in a React project

Currently, I am in the process of developing a React application and have encountered an issue with components disappearing upon refresh. It seems to be related to React Router, suggesting that I may be implementing it incorrectly. This is what my App.js ...

What is the method for adjusting the alignment of text in each separate header cell within ui-grid?

Check out this ui-grid example I am currently using a grid similar to the one shown in the image. I would like to adjust the text alignment of the first header cell to left and the second header cell to center. Is there a way to achieve this? Here is a P ...

The pause button will still function, even if the scrolling feature is enabled

I've successfully implemented a feature that pauses and plays the video on scroll when it reaches a certain pixel height. However, I'm facing an issue where the code automatically plays the video whenever the scroll position is more than 13500px ...

Unlock the Power of Angular: Leveraging ViewEncapsulation.Native to Access HTML Elements

I am encountering an issue where I am receiving an error when trying to access an HTML element by ID. The problem arises when I attempt to access the classList upon a user clicking a button to apply a different style class to the element. The class list an ...

Execute operations on element itself rather than the output of document.getElementbyId

I encountered an issue involving an HTML element with the ID of BaseGridView. When I call a function directly on this element, everything works perfectly. However, if I use document.getElementById() to retrieve the element and then call the function, it do ...

Create a new CSS rule within a class, and remember to save the changes to

Upon opening page 1.html, I utilize JavaScript to dynamically add a background image to the body of the page. To achieve this, I use the following code: document.body.style.backgroundImage = "url(http://www.example.com/image.jpg)"; This code effectively ...

The React.useCallback hook in Cube.js is missing a dependency, specifically 'pivotConfig'. This could potentially cause unexpected behavior in the application

After multiple attempts at creating a straightforward dashboard using Cube.js with Windows 10 and MySQL version 8, I am feeling frustrated. Initially, I experimented with a JavaScript backend, struggled through the installation process for days, then attem ...

How to insert space after every item generated by ng-repeat in AngularJS

I'm looking to evenly distribute elements based on this inquiry How to distribute li elements equally? I am utilizing angular with jade: ul li(ng-repeat="item in items") {{item.name}} However, ng-repeat does not create newlines after each element ...