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

how to execute Vue-Js method just one time

Is there a way to add a random number (ranging from 0 to the price of an item) to one of the data properties in Vue.js, but only once when the page is initially loaded? I am unable to use mounted and computed because I need to pass a parameter to the funct ...

Issue with Angular controller not refreshingalternatively:Angular

I just started reading an AngularJS book by O'Reilly and I encountered a problem with the first example. Instead of seeing "hello" as expected in place of "{{greeting.text}}", it displays exactly that. I have double-checked my angular linking and even ...

Combining various datasets with identical X values in a D3 bar graph

I'm currently working on creating a grouped bar chart to display performance test results using D3 for the first time. The X axis should represent parallelism, indicating the number of threads used, while the Y axis will show the duration in millisec ...

Exclude a specific tag from a div in JavaScript

I need help selecting the text within an alert in JavaScript, excluding the <a> tag... <div id="addCompaniesModal" > <div class="alertBox costumAlertBox" style="display:inline-block;"> <div class="alert alert-block alert- ...

The standard process and organization of a project using AngularJS in conjunction with Python Flask

As someone new to the MV* client-side framework craze, I find myself leaning towards AngularJS over Knockout, Ember, or Backbone. However, I'm unsure about the workflow involved. Should I start by developing a client-side application in AngularJS and ...

Can VueJS support multiple v-slots in a component?

I recently set up vee-validate v3.0 for validation in my project and everything was going smoothly until I tried to style my elements. Despite following the documentation on styling and making changes to the vee-validate config, I encountered a new issue - ...

Remove attributes from a collection of objects

Here is an array of objects: let array = [{ firstName: "John", lastName : "Doe", id:5566, weight: 70 },{ firstName: "Francis", lastName : "Max", id:5567, weight: 85 }]; I am looking to remove the properties "lastName" and "weight" for all obj ...

bring in all the files located within the Directory

Is there a way to import all CSS files from a specific folder without having to import each file individually? Looking to import assets/css/* ? <link href="<?php echo base_url(); ?>assets/css/*" rel="stylesheet"/> <title&g ...

Managing the layout with React Native Flexbox to evenly distribute items

Check out this React Native Demo I put together featuring Santa images being added and removed in a Flexbox. Bunch of Santas I noticed that when there are more than 3 Santas, the layout shifts to the left. I'm curious about how to keep the Santas ce ...

jQuery ajax doesn't function properly on the server, it only works locally

When I send a jQuery Ajax request from my front-end to the back-end to retrieve values for calculations, it works perfectly on my local web server. However, when I try it online, all I get is a result of 0 in my calculations, indicating that the Ajax respo ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

javascript add items to a container

I created a looping animation that features dynamic words, but I'm struggling to append all the spans into the <div id"wordcloud"></div>. Any assistance with this would be greatly appreciated. var interval = 100; var width = 800; var he ...

React beautiful dnd and Material UI list encountering compatibility problem

I recently encountered an issue while using react beautiful dnd to create a rearrangeable Material UI List. Everything was working correctly, except for the ListItemSecondaryAction within the list. When dragging a list item, the ListItemText and ListItemIc ...

The process of integrating a Loader in Javascript

I am in need of a simple "page loading" animation while my photo is being uploaded. Unfortunately, when I tried using the "blockUI" JavaScript for this purpose, it didn't seem to work with my form. For uploading the image, I have employed a div as a ...

What is the best way to retrieve the value of this event in a React component?

Is there a way to retrieve the value of an input field? Typically, I would use event.target.value to do so. However, in this case, that method is not viable because the path of event.target leads me to an li element instead: This issue arises with a compo ...

Having trouble with dynamic path generation for router-link in Vuejs when using a v-for loop?

//main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld.vue"; Vue.use(VueRouter); const router = new VueRouter({ routes: [{ path: "/", component: HelloWorld }] } ...

Assign the ngClick event handler to the capturing phase

Can the ngClick event handler be configured to work in the capturing phase, as discussed in this informative article? I am interested in stopping events from propagating down to child elements and then back up again when a specific condition is met for t ...

Let's leverage the power of Node.js and Express with the Jade templating

My goal is to iterate over an array within a jade layout file named lessons.jade: each lesson in myLessons ul.nav.pull-center: li.dropdown.nav.text-center .btn.btn-default.dropdown-toggle.btn-lg.btn-block(data-toggle="dropdown ...

What is the best approach to create a JavaScript search filter function spanning two pages?

Page1.html has a form with a drop-down menu containing options Color and Shape. There is also a submit button. Assuming Page2.html displays various shapes like Blue Square, Red Square, Blue Circle, Red Circle, is it feasible to create a JavaScript file th ...

Manipulating video volume using JavaScript injection

My web page includes a video, and I have successfully used JavaScript injection to control the play/pause functionality. Now, I am looking to also adjust the volume based on percentage. How can I create a function that decreases or increases the volume acc ...